I try to get rid of an ugly javscript eval method (Cause we all know it is unsecure).
I have the following problem. I build a dynamic searchstring.
Depends on the TLD a user decided to search for.
Here is my code:
if (tld == 0) {
var searchString = 'value.tld != ""';
}
if (tld == 1) {
var searchString = 'value.tld == "de"';
}
if (tld == 2) {
var searchString = 'value.tld == "com" || value.tld == "net" || value.tld == "org" || value.tld == "info" || value.tld == "biz"';
}
if (tld == 3) {
var searchString = 'value.tld == "io"';
}
Depending on the search parameter 'searchstring', I build this routine with eval:
if (eval(searchString)) {
// Do something special, depends on the tld variable
}
How can i rebuild this without using 'eval'. The premission is, that the first part of the code is beeing untouched.
Thanks in advance
Nick
How about:
let choices = {
1: ['de'],
2: ['com', 'net', 'org', 'info', 'biz'],
3: ['io']
};
function check(tldparam) {
if (tld === 0) {
return value.tld !== "";
} else {
return tld === tldparam && choices[tldparam].includes(value.tld);
}
}
And we test it like:
// Got this value from somewhere
let tld = 2;
let value = {tld: 'net'};
// This is my checking criterion
let tldparam = 2;
if (check(tldparam)) {
// Do something special, depends on the tld variable
}
Does it serve your purpose?
I am trying to modify a WordPress plugin which activates a game script when a button is pressed. I would like to be able to activate it with a combination of key presses instead (Shift + Control + F).
I have attempted wrapping the entire script in a keypress function, however, this did not work. I have confirmed that script is loaded via console log but pressing the key combination does not do anything.
Original code:
PHP
<?php
...
/* Insert the button*/
switch ($asteroids_buttonopt) {
case "push-1":
echo '<div><p style="text-align: center;">
<a href="#" onclick="'.$asteroids_start.'"><button>Click to Play Asteroids!!!</button>
</a></p></div>';
break;
...
}
?>
JS
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function startAsteroids(color,address) {
var ver = getInternetExplorerVersion();
if(ver>=0){
color = typeof(color) != 'undefined' ? color : 'black';
document.onkeydown = function(ev) {
var key;
ev = ev || event;
key = ev.keyCode;
if(key == 37 || key == 38 || key == 39 || key == 40) {
//e.cancelBubble is supported by IE - this will kill the bubbling process.
ev.cancelBubble = true;
ev.returnValue = false;
}
}
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
else{
color = typeof(color) != 'undefined' ? color : 'black';
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
}
Any help would be greatly appreciated. The original plugin 'Asteroid Widget' was abandoned 8 years ago so I cannot seek help from the developers.
Instead of wrapping the entire page content, you should add the following onkeypress function to the end of the JS file.
Required Function
window.onkeypress=function(e){
if(e.ctrlKey && e.shiftKey && e.code==='KeyF' ){
startAsteroids('','/wp-content/plugins/asteroids-widget/gears/play-asteroids-yellow.min.js');
}
}
Complete resulting file
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function startAsteroids(color,address) {
var ver = getInternetExplorerVersion();
if(ver>=0){
color = typeof(color) != 'undefined' ? color : 'black';
document.onkeydown = function(ev) {
var key;
ev = ev || event;
key = ev.keyCode;
if(key == 37 || key == 38 || key == 39 || key == 40) {
//e.cancelBubble is supported by IE - this will kill the bubbling process.
ev.cancelBubble = true;
ev.returnValue = false;
}
}
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
else{
color = typeof(color) != 'undefined' ? color : 'black';
var s =document.createElement('script');
s.type='text/javascript'
document.body.appendChild(s);
s.src = address;
void(0);
return false;
}
}
window.onkeypress=function(e){
if(e.ctrlKey && e.shiftKey && e.code==='KeyF' ){
startAsteroids('','/wp-content/plugins/asteroids-widget/gears/play-asteroids-yellow.min.js');
}
}
I am trying for smart search on my web page, so in my search on Click event I am getting Text which is selected in same textarea and but when I try with On keypress I'm unable to do find text of selected item. I am using jquery1.4.2 and tried option:select but still fail to do so...
My Code for click
$(document).ready(function() {
$('#ctl00_ContentPlaceHolder1_smartSearch').keyup(function(e) {
var str = document.getElementById('ctl00_ContentPlaceHolder1_smartSearch');
//alert("hi");
if (str.value.length >= 2) {
if (e.keyCode != 40 && e.keyCode != 38 && e.keyCode != 13) {
var str1 = str.value;
var str2 = str1.replace(' ', '+')
var url = "../SiteCache/90D/SmartGetQuoteData.aspx?Type=EQ&text=" + str2;
$("#ajax_response_smart").load(url);
}
$("#ajax_response_smart").show();
$('#listEQ li').live('click', function() {
var selected = $(this).text();
$("#ajax_response_smart").remove();
if (selected != "") {
var scripcode = selected.split("|");
document.getElementById('ctl00_ContentPlaceHolder1_smartSearch').value = scripcode[0];
document.getElementById('ctl00_ContentPlaceHolder1_hdnCode').value = scripcode[2];
}
});
var $listItems = $('#listEQ li');
var key = e.keyCode,
$selected = $listItems.filter('.ui-state-hover'),
$current;
if (key != 40 && key != 38 && key != 13)
{ return; }
else {
$listItems.removeClass('ui-state-hover');
}
if (key == 40) // Down key
{
if (!$selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
}
else {
$current = $selected.next();
}
}
else if (key == 38) // Up key
{
if (!$selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
}
else {
$current = $selected.prev();
}
}
else if (key == 13) {
}
}
else {
$("#ajax_response_smart").hide();
}
if (typeof $current != "undefined") {
$current.addClass('ui-state-hover');
}
});
$("#ajax_response_smart").mouseover(function() {
var $listItems1 = $('#listEQ li');
$selected1 = $listItems1.filter('.ui-state-hover');
$(this).find("#listEQ li").mouseover(function() {
($selected1).removeClass("ui-state-hover");
$(this).addClass("ui-state-hover");
});
$(this).find("#listEQ li").mouseout(function() {
$(this).removeClass("ui-state-hover");
});
});
});
Please Suggest and Thanks in advance
hey i got my the answer i called the keypress event on my textbox in aspx page and from there i came on the currently paosted js page then on keypress event i got value.i.e not able to use keyup event to detect enter
Is there any object or method that returns data about the browser, client-side?
For example, I need to detect if the browser is IE (Interner Explorer). Following is the code snippet.
function isInternetExplorer()
{
if(navigator.appName.indexOf("Microsoft Internet Explorer") != -1)
{
return true;
}
return false;
}
Is there a better way?
JavaScript side - you can get browser name like these ways...
if(window.navigator.appName == "") OR if(window.navigator.userAgent == "")
This is pure JavaScript solution. Which I was required.
I tried on different browsers. It is working fine. Hope it helps.
How do I detect the browser name ?
You can use the navigator.appName and navigator.userAgent properties. The userAgent property is more reliable than appName because, for example, Firefox (and some other browsers) may return the string "Netscape" as the value of navigator.appName for compatibility with Netscape Navigator.
Note, however, that navigator.userAgent may be spoofed, too – that is, clients may substitute virtually any string for their userAgent. Therefore, whatever we deduce from either appName or userAgent should be taken with a grain of salt.
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) {
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>');
From the source javascripter.net
EDIT: Since the answer is not valid with newer versions of jquery As jQuery.browser is deprecated in ver 1.9, So Use Jquery Migrate Plugin for that matter.
Original Answer
jQuery.browser
jQuery.browser
and
jQuery.browser.version
is your way to go...
I found a purely Javascript solution here that seems to work for major browsers for both PC and Mac. I tested it in BrowserStack for both platforms and it works like a dream. The Javascript solution posted in this thread by Jason D'Souza is really nice because it gives you a lot of information about the browser, but it has an issue identifying Edge which seems to look like Chrome to it. His code could probably be modified a bit with this solution to make it work for Edge too. Here is the snippet of code I found:
var browser = (function (agent) {
switch (true) {
case agent.indexOf("edge") > -1: return "edge";
case agent.indexOf("edg") > -1: return "chromium based edge (dev or canary)";
case agent.indexOf("opr") > -1 && !!window.opr: return "opera";
case agent.indexOf("chrome") > -1 && !!window.chrome: return "chrome";
case agent.indexOf("trident") > -1: return "ie";
case agent.indexOf("firefox") > -1: return "firefox";
case agent.indexOf("safari") > -1: return "safari";
default: return "other";
}
})(window.navigator.userAgent.toLowerCase());
console.log(window.navigator.userAgent.toLowerCase() + "\n" + browser);
UPDATED
Here is a better version from BSlink's answer which has a few problems. There are too many edits in the queue for me to submit one in his answer so I'm editing my own answer to share the corrections:
const agent = window.navigator.userAgent.toLowerCase();
const browser =
agent.indexOf('edge') > -1 ? 'edge'
: agent.indexOf('edg') > -1 ? 'chromium based edge'
: agent.indexOf('opr') > -1 && window.opr ? 'opera'
: agent.indexOf('chrome') > -1 && window.chrome ? 'chrome'
: agent.indexOf('trident') > -1 ? 'ie'
: agent.indexOf('firefox') > -1 ? 'firefox'
: agent.indexOf('safari') > -1 ? 'safari'
: 'other';
console.log(`${agent}\n${browser}`);
In c# you your browser name using:
System.Web.HttpBrowserCapabilities browser = Request.Browser;
For details see a link.
http://msdn.microsoft.com/en-us/library/3yekbd5b%28v=vs.100%29.aspx
and in Client side:
JQuery:
jQuery.browser
For details see a link:
http://api.jquery.com/jQuery.browser/
I liked Sintrias's answer but I wanted to uppdate a bit with a slightly more modern syntax.
const userAgent = window.navigator.userAgent.toLowerCase();
const browser =
userAgent.indexOf('edge') > -1 ? 'edge'
: userAgent.indexOf('edg') > -1 ? 'chromium based edge'
: userAgent.indexOf('opr') > -1 && !!window.opr ? 'opera'
: userAgent.indexOf('chrome') > -1 && !!window.chrome ? 'chrome'
: userAgent.indexOf('trident') > -1 ? 'ie'
: userAgent.indexOf('firefox') > -1 ? 'firefox'
: userAgent.indexOf('safari') > -1 ? 'safari'
: 'other';
console.log(`${userAgent.toLowerCase()}\n${browser}`);
The browser discloses it in navigator.userAgent. If you're using jQuery, you're better off using jQuery.browser as #Rab Nawaz said. However, as the API documentation says, it's better to check for feature support if possible. Quoting the documentation:
We recommend against using this property; please try to use feature detection instead (see jQuery.support). jQuery.browser may be moved to a plugin in a future release of jQuery.
Here is a code example:
function isIE() {
if (window.jQuery) {
return jQuery.browser.msie || false;
} else {
// adapted from jQuery's source:
return navigator.userAgent.toLowerCase().indexOf('msie') >= 0;
}
}
This is answered in
How to detect Safari, Chrome, IE, Firefox and Opera browser?
Check this fiddle.
Hope this helps.
It's all about what you really want to do, but in times to come and right now, the best way is avoid browser detection and check for features. like Canvas, Audio, WebSockets, etc through simple javascript calls or in your CSS, for me your best approach is use a tool like ModernizR:
Unlike with the traditional—but highly unreliable—method of doing “UA sniffing,” which is detecting a browser by its (user-configurable) navigator.userAgent property, Modernizr does actual feature detection to reliably discern what the various browsers can and cannot do.
If using CSS, you can do this:
.no-js .glossy,
.no-cssgradients .glossy {
background: url("images/glossybutton.png");
}
.cssgradients .glossy {
background-image: linear-gradient(top, #555, #333);
}
as it will load and append all features as a class name in the <html> element and you will be able to do as you wish in terms of CSS.
And you can even load files upon features, for example, load a polyfill js and css if the browser does not have native support
Modernizr.load([
// Presentational polyfills
{
// Logical list of things we would normally need
test : Modernizr.fontface && Modernizr.canvas && Modernizr.cssgradients,
// Modernizr.load loads css and javascript by default
nope : ['presentational-polyfill.js', 'presentational.css']
},
// Functional polyfills
{
// This just has to be truthy
test : Modernizr.websockets && window.JSON,
// socket-io.js and json2.js
nope : 'functional-polyfills.js',
// You can also give arrays of resources to load.
both : [ 'app.js', 'extra.js' ],
complete : function () {
// Run this after everything in this group has downloaded
// and executed, as well everything in all previous groups
myApp.init();
}
},
// Run your analytics after you've already kicked off all the rest
// of your app.
'post-analytics.js'
]);
a simple example of requesting features from javascript:
http://jsbin.com/udoyic/1
This code will return "browser" and "browserVersion"
Works on 95% of 80+ browsers
var geckobrowsers;
var browser = "";
var browserVersion = 0;
var agent = navigator.userAgent + " ";
if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("like Gecko") != -1){
geckobrowsers = agent.substring(agent.indexOf("like Gecko")+10).substring(agent.substring(agent.indexOf("like Gecko")+10).indexOf(") ")+2).replace("LG Browser", "LGBrowser").replace("360SE", "360SE/");
for(i = 0; i < 1; i++){
geckobrowsers = geckobrowsers.replace(geckobrowsers.substring(geckobrowsers.indexOf("("), geckobrowsers.indexOf(")")+1), "");
}
geckobrowsers = geckobrowsers.split(" ");
for(i = 0; i < geckobrowsers.length; i++){
if(geckobrowsers[i].indexOf("/") == -1)geckobrowsers[i] = "Chrome";
if(geckobrowsers[i].indexOf("/") != -1)geckobrowsers[i] = geckobrowsers[i].substring(0, geckobrowsers[i].indexOf("/"));
}
if(geckobrowsers.length < 4){
browser = geckobrowsers[0];
} else {
for(i = 0; i < geckobrowsers.length; i++){
if(geckobrowsers[i].indexOf("Chrome") == -1 && geckobrowsers[i].indexOf("Safari") == -1 && geckobrowsers[i].indexOf("Mobile") == -1 && geckobrowsers[i].indexOf("Version") == -1)browser = geckobrowsers[i];
}
}
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Gecko/") != -1){
browser = agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).substring(0, agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Clecko/") != -1){
browser = agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).substring(0, agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0"){
browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(";"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 == agent.length-1){
browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ")[agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ").length-1];
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 != agent.length-1){
if(agent.substring(agent.indexOf(") ")+2).indexOf("/") != -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf("/"));
if(agent.substring(agent.indexOf(") ")+2).indexOf("/") == -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf(" "));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(0, 6) == "Opera/"){
browser = "Opera";
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
if(agent.substring(agent.indexOf("(")+1).indexOf(";") != -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(";"));
if(agent.substring(agent.indexOf("(")+1).indexOf(";") == -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(")"));
} else if(agent.substring(0, agent.indexOf("/")) != "Mozilla" && agent.substring(0, agent.indexOf("/")) != "Opera"){
browser = agent.substring(0, agent.indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else {
browser = agent;
}
alert(browser + " v" + browserVersion);
You can also get an array of brands that is used by user using the following way:
let browser = window.navigator.userAgentData.brands;
console.log('browser', browser);
Based on is.js you can write a helper file for getting browser name like this-
const Browser = {};
const vendor = (navigator && navigator.vendor || '').toLowerCase();
const userAgent = (navigator && navigator.userAgent || '').toLowerCase();
Browser.getBrowserName = () => {
if(isOpera()) return 'opera'; // Opera
else if(isChrome()) return 'chrome'; // Chrome
else if(isFirefox()) return 'firefox'; // Firefox
else if(isSafari()) return 'safari'; // Safari
else if(isInternetExplorer()) return 'ie'; // Internet Explorer
}
// Start Detecting browser helpers functions
function isOpera() {
const isOpera = userAgent.match(/(?:^opera.+?version|opr)\/(\d+)/);
return isOpera !== null;
}
function isChrome() {
const isChrome = /google inc/.test(vendor) ? userAgent.match(/(?:chrome|crios)\/(\d+)/) : null;
return isChrome !== null;
}
function isFirefox() {
const isFirefox = userAgent.match(/(?:firefox|fxios)\/(\d+)/);
return isFirefox !== null;
}
function isSafari() {
const isSafari = userAgent.match(/version\/(\d+).+?safari/);
return isSafari !== null;
}
function isInternetExplorer() {
const isInternetExplorer = userAgent.match(/(?:msie |trident.+?; rv:)(\d+)/);
return isInternetExplorer !== null;
}
// End Detecting browser helpers functions
export default Browser;
And just import this file where you need.
import Browser from './Browser.js';
const userBrowserName = Browser.getBrowserName() // return your browser name
// opera | chrome | firefox | safari | ie
Is there a way to find the selected text in an HTML document if the text may be within one of its frames (or iframes)?
If the document has no frames it's simple:
var text;
if (document.getSelection) {
// Firefox and friends
text = document.getSelection();
} else if (document.selection) {
// IE
text = document.selection.createRange();
}
if (text == undefined || text == '') {
// Iterate over all textarea elements and see if one of them has selection
var areas = document.getElementsByTagName('textarea');
for(var i = 0; i = areas.length; i++) {
if(areas[i].selectionStart != undefined &&
areas[i].selectionStart != areas[i].selectionEnd){
text = areas[i].value.substring(areas[i].selectionStart, a[i].selectionEnd);
break;
}
}
}
// Now if document has selected text, it's in text
So this works cross-browser (although not very pretty).
The problem is when the document contains frames or iframes.
Frames have their own document, so just using the code above is not enough.
One could potentially iterate over the frames tree and search for selected text in one of them, however in general frames can have content from different domains, so even if I were to iterate over all frames and over all subframes etc of the root document in search of selected text I would not have had the permission to access their HTML, right? So I wouldn't be able to get their selected text.
Is there a (simple) reliable way of finding the selected text on a web page even if the page contains frames?
Thanks
To answer my own question, after a bit more investigation:
So, if frames are of different domains then there's nothing you can do about it since you have no permission accessing their dom. However, in the common case where all frames are on the same domain (e.g. gmail) just iterate theme all like a tree. Here's the code that accomplishes that:
The code below is for a bookmarklet that counts chars and words of the selected text:
javascript:(function(){
// Function: finds selected text on document d.
// #return the selected text or null
function f(d){
var t;
if (d.getSelection) t = d.getSelection();
else if(d.selection) t = d.selection.createRange();
if (t.text != undefined) t = t.text;
if (!t || t=='') {
var a = d.getElementsByTagName('textarea');
for (var i = 0; i < a.length; ++i) {
if (a[i].selectionStart != undefined && a[i].selectionStart != a[i].selectionEnd) {
t = a[i].value.substring(a[i].selectionStart, a[i].selectionEnd);
break;
}
}
}
return t;
};
// Function: finds selected text in document d and frames and subframes of d
// #return the selected text or null
function g(d){
var t;
try{t = f(d);}catch(e){};
if (!t || t == '') {
var fs = d.getElementsByTagName('frame');
for (var i = 0; i < fs.length; ++i){
t = g(fs[i].contentDocument);
if(t && t.toString() != '') break;
}
if (!t || t.toString() == '') {
fs = d.getElementsByTagName('iframe');
for (var i = 0; i < fs.length; ++i){
t = g(fs[i].contentDocument);
if(t && t.toString() != '') break;
}
}
}
return t;
};
var t= g(document);
if (!t || t == '') alert('please select some text');
else alert('Chars: '+t.toString().length+'\nWords: '+t.toString().match(/(\S+)/g).length);
})()
#Ran Excellent answer to your own question. However, if the iframe document is undefined then the function fails. I added a conditional to check for this, now it works on every site I've tried including Gmail. if ((!t || t == '') && d) Thanks again for the great code.
var getSelectedText = function(){
// Function: finds selected text on document d.
// #return the selected text or null
function f(d){
var t;
if (d.getSelection) t = d.getSelection();
else if(d.selection) t = d.selection.createRange();
if (t.text != undefined) t = t.text;
if (!t || t=='') {
var a = d.getElementsByTagName('textarea');
for (var i = 0; i < a.length; ++i) {
if (a[i].selectionStart != undefined && a[i].selectionStart != a[i].selectionEnd) {
t = a[i].value.substring(a[i].selectionStart, a[i].selectionEnd);
break;
}
}
}
return t;
};
// Function: finds selected text in document d and frames and subframes of d
// #return the selected text or null
function g(d){
var t;
try{t = f(d);}catch(e){console.log('ERROR: ',e);};
if ((!t || t == '') && d){
var fs = d.getElementsByTagName('frame');
for (var i = 0; i < fs.length; ++i){
t = g(fs[i].contentDocument);
if(t && t.toString() != '') break;
}
if (!t || t.toString() == '') {
fs = d.getElementsByTagName('iframe');
for (var i = 0; i < fs.length; ++i){
t = g(fs[i].contentDocument);
if(t && t.toString() != '') break;
}
}
}
return t;
};
var t= g(document);
if (!t || t == '') ;
else return t.toString();
}