JavaScript browser detection? - javascript

I need to add a certain kind of support for touch devices on a current project. As this is the first time I have to do something like this, I took a look at the code of some "well made" websites to see how they do that.
One page does something like this:
if(document.querySelectorAll && (navigator.platform == "iPad" || navigator.platform.substring(0, 6) == "iPhone" || navigator.platform == "iPod" || navigator.userAgent.indexOf('Android') > -1)) {...}
I tested it on all the devices I have at hand and it works, but please tell me, is it alright to do it this way? Is there a "correct" way to do it?
I am asking because here I've read that browser detection should be avoided, instead object detection should be used. Now I see that they are also testing for document.querySelectorAll which is object detection, so maybe everything that comes after it is just some sort of safety net?

Browser detection should be avoided, yes. Because a browser can change.
Today, maybe google Chrome don't support a feature. But tomorrow Chrome should be updated and support it.
So if you do something like if (!isGoogleChrome()), the day when Chrome is updated, you must update your code.
You should do object detection.
For example, if you want to make sure that a function/object is here, just test it :
if (document.querySelectorAll !== undefined) {
//...
}
You could also use http://modernizr.com/ , it can detect the current browser features for you.

The code you use is very very sensible : any simple character insertion at the start would make it fail.
You could replace it with something like
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|Mini/i.test(navigator.userAgent)) { ...
But you should be aware that detecting devices is dangerous as they might be more diverse that what one thinks : some have better CPU, network access or screen than some desktop browsers. So for most uses, it's better to detect the features you need.
This detection can legitimately, in my opinion, be used to detect touch screens if you plan to maintain your site depending on available devices but there are other solutions, for example libraries like Modernizr or specific tests.

Related

JavaScript not working in IE but works in FireFox?

post_form_id = escape(findelementbyname("post_form_id"));
fb_dtsg = escape(document.getElementsByName("fb_dtsg")[0].value);
cookie_user_uid = document.cookie.match(/c_user=(\d+)/)[1];
xhpc_composerid = escape(findelementbyname("xhpc_composerid"));
It seems as if post_form_id and fb_dtsg cannot execute properly in Internet explorer, but work in Firefox?
What would I have to change to have it working in both?
One Question : Are you able to search by Id instead? If so, getElementById(...) will be a better choice.
To get elements by name, you will use getElementsByName("...") - but that will return an array of elements, from which you will need to take the first item.
Typically what you describe regarding inconsistency across browsers is caused by syntax problems...
I believe that this:
findelementbyname(...)
should be this:
FindElementByName(...)
Also run your code through an online syntax checker like JSLint
Although you can make javascript cross browser compatible without extra libraries (such as JQuery), it can often become unneccesarily painful to do so.
I would recommend the use of JQuery.

browser identification

I want to identify if the broswer is IE then goto if block, other browser to else block in Java script.
I have one code here,
var browserName=navigator.appName;
if(browserName == "Microsoft Internet Explorer"){
IE code
}
else{
Other code
}
but i want to know is there any other way of implementing it?
Rather than do browser sniffing, you should do feature detection. Later versions of IE may support standards compliant stuff that in older versions you needed to work around or use MS-specific stuff.
Microsoft themselves have written up about the best way to do this and provide examples of both bad code (via sniffing) and good code (via detection). Make sure you go down the "good code" route.
I just started using this script to identify browser, version, and OS:
http://www.quirksmode.org/js/detect.html
If you are needing to use different code based on browser support for certain objects or methods, it's usually better to use object or method detection instead of browser detection. I use the browser detection for collecting statistics on my users, not for enabling or disabling features.
Quirksmode has a short article about why you don't use browser detection this way: http://www.quirksmode.org/js/support.html It's also linked from the browser detection script.
I found that This task is quite difficult as browsers all have similar names and different userAgent strings, so this is my Conditional statement to identify browsers.
I used this to identify the browser for different style sheets.
function styc()
{
var str = navigator.userAgent;
var res = navigator.userAgent.match(/Trident/);
var res2 = navigator.userAgent.match(/Firefox/);
if(res=="Trident"||res2=="Firefox")
{
//alert(navigator.userAgent);//for testing
document.getElementById('IE_fix').setAttribute("href", "IE_fix.css");
}
else
{
//alert("no");//for testing
document.getElementById('IE_fix').setAttribute("href", "mt_default.css");
}
}
Find a unique word in the userAgent string match it and check if the condition is true or not true depending on what you are doing.
The unique word I found for IE is Trident, and also identifies IE versions according to MicroSoft(not positive on this).

Which is a better way to detect a client's user-agent?

I am interested if which would be the best place to detect the client's user-agent, client-side (javascript) or server-side? I brought up the question due to the fact that some IE8 users are getting a message saying they're using IE6.
The short and correct answer is : do not use anything that relies on UserAgent sniffing.
To reliable be able to adjust code paths you should test for the specific 'thing' that the codepath is adjusted for, primarily features. This is called Feature Detection.
So if feature X is supported we do this, if not we do that.
Deducing if a feature is supported based on which UserAgent is present will rapidly fail, especially when new browsers come to the marked.
Take the following example, which can actually be found in several major libraries (!)
if (isIE8) {
// use new feature provided by IE8
} else if (isIE7) {
// use not so new feature provided by IE7 (and IE8)
} else {
// use fallback for all others (which also works in IE7 and IE8)
}
What do you think happens when IE9 comes along?
The correct pattern in this case would be
if ("addEventListener" in foo) {
// use DOM level 2 addEventListener to attach events
foo.addEventListener(...
} else if ("attachEvent" in foo) {
// use IE's proprietary attachEvent method
foo.attachEvent(...
} else {
// fall back to DOM 0
foo["on" + eventName] = ....
}
The User-agent available on both sides should be the same, unless there's funny stuff going on, which normally isn't.
If you want to show a message to IE6 users, I suggest you use conditional comments. They're an IE-specific feature and work very well for detecting IE versions.
The information found through client or server-side detection is basically the same.
Keep in mind it is extremely easy to spoof what browser you're in. There is no fail-safe way to detect all browser types accurately.
i don't know how you're checking for the user agent, but i'd do this way:
<%=
case request.env['HTTP_USER_AGENT']
when /Safari/
"it's a Mac!"
when /iPhone/
"it's a iPhone"
else
"i don't know :("
end
%>
checking directly in the user request seems to be the most consistent way to verify the user browser. And the request.env is avaliable in your controller and views, so you could pass this to rjs if needed.
For those who need to get the actual user-agent using JavaScript, you can use navigator.userAgent

disable javascript on ie browsers

is there a way to disable a certain script for all ie browsers?
You can make use of conditional compilation to determine if the client is using MSIE.
var IE = /*#cc_on!#*/false;
which can be used as
if (IE) {
// IE.
} else {
// Others.
}
Only in IE, the ! will be compiled and taken in the expression, resulting in a new expression !false, which is logically true. This works better than $.browser.msie because it can be fooled by the useragent and also better than document.all because it would affect certain Opera versions as well.
That said, what is it you're trying to disable? You can on the other hand also make use of feature detection. Here's a discussion about this: Browser detection versus feature detection
I wouldn't recommend this, but:
if(!$.browser.msie) {
//non IE script
}
I would fix the script to work in IE, or exclude it based on some feature the browser doesn't support...not just because it's IE. With any browser a feature could be added via an update tomorrow, and your script would still exclude it. See $.support for more on feature detection.
Excluding something from running because "it isn't supported" is a perfectly valid scenario. However, excluding something because "IE doesn't support it...when I wrote this code" isn't a good approach. Instead, check if the feature that you need is present, and the user gets the richest experience possible in their current browser.
You could not include the javascript at all for IE browsers using Microsoft's recommended way of inserting a conditional comment:
<!--[if !IE]>
<script src="myscript.js" type="text/javascript"></script>
<![endif]-->
or simply wrap the code you want to exclude in the comment.
If you're speaking of IE 6, you can crash it by calling this function :
function crash_IE6() {for(x in document.open);}
Seriously, the most use way of deteting IE is checking the presence of document.all... but it still isn't a good thing.
You should nerver check what browser your script is running on... you should just check the presence of the needed methods.

Safe feature-based way for detecting Google Chrome with Javascript?

As the title states, I'd be interested to find a safe feature-based (that is, without using navigator.appName or navigator.appVersion) way to detect Google Chrome.
By feature-based I mean, for example:
if(window.ActiveXObject) {
// internet explorer!
}
Edit: As it's been pointed out, the question doesn't make much sense (obviously if you want to implement a feature, you test for it, if you want to detect for a specific browser, you check the user agent), sorry, it's 5am ;) Let me me phrase it like this: Are there any javascript objects and/or features that are unique to Chrome...
isChrome = function() {
return Boolean(window.chrome);
}
This answer is very outdated, but it was very relevant back then in the stone age.
I think feature detect is more usefull than navigator.userAgent parsing, as I googled Opera ambiguosity here. Nobody can know if IE16 will parse the /MSIE 16.0;/ regexp - but we can be quite sure, there will be the document.all support. In real life, the features are usually synonyms for the browsers, like: "No XMLHttpRequest? It is the f....d IE6!"
No nonIE browser supports document.all, but some browsers like Maxthon can scramble the userAgent. (Of course script can define document.all in Firefox for some reason, but it is easilly controllable.) Therefore I suggest this solution.
Edit Here I found complete resources.
Edit 2 I have tested that document.all is also supported by Opera!
var is = {
ff: window.globalStorage,
ie: document.all && !window.opera,
ie6: !window.XMLHttpRequest,
ie7: document.all && window.XMLHttpRequest && !XDomainRequest && !window.opera,
ie8: document.documentMode==8,
opera: Boolean(window.opera),
chrome: Boolean(window.chrome),
safari: window.getComputedStyle && !window.globalStorage && !window.opera
}
Using is simple:
if(is.ie6) { ... }
Not exactly an answer to the question... but if you are trying to detect a specific browser brand, the point of feature-checking is kind of lost. I highly doubt any other browsers are using the Chrome userAgent string, so if your question is 'is this browser Chrome', you should just look at that. (By the way, window.ActiveXObject does not guarantee IE, there are plug-ins for other browsers that provide this object. Which kind of illustrates the point I was trying to make.)
For all the standards nazis... sometimes you might want to use bleeding "standard technologies" which aren't just yet standard but they will be... Such as css3 features.
Which is the reason why I found this page.
For some reason, Safari runs a combo of border-radius with box-shadow just fine, but chrome doesn't render the combination correctly. So it would be nice to find a way to detect chrome even though it is webkit to disable the combination.
I've ran into hundreds of reasons to detect a specific browser/version which usually ends up in scrapping an idea for a cool feature because what I want to do is not supported by the big evil...
But sometimes, some features are just too cool to not use them, even if they aren't standardized yet.
So, if you accept Marijn's point and are interested in testing the user agent string via javascript:
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
(Credit to: http://davidwalsh.name/detecting-google-chrome-javascript )
Here's a really nice analysis/breakdown of the chromes user agent string: http://www.simonwhatley.co.uk/whats-in-google-chromes-user-agent-string
I often use behavior/capability detection. Directly check whether the browser supports functionality before working around it, instead of working around it based on what might be the browser's name (user-agent).
A problem with browser-specific workarounds, is you don't know if the bug has been fixed or if the feature is supported now. When you do capability detection, you know the browser does or doesn't support it directly, and you're not just being browser-ist.
http://diveintohtml5.ep.io/everything.html
You shouldn't be detecting Chrome specifically. If anything, you should be detecting WebKit, since as far as page rendering is concerned, Chrome should behave exactly like other WebKit browsers (Safari, Epiphany).
If you need not only to detect WebKit, but also find out exactly what version is being used, see this link: http://trac.webkit.org/wiki/DetectingWebKit
But again, as other people said above, you shouldn't detect browsers, you should detect features. See this ADC article for more on this: http://developer.apple.com/internet/webcontent/objectdetection.html
One reason you might need to know the browser is Chrome is because it 'is' so damn standards compliant. I have already run into problems with old JavaScript code which I thought was standards compliant (by FF or Opera standards - which are pretty good), but Chrome was even more picky. It forced me to rewriting some code, but at times it might be easier to use the if(isChrome) { blah...blah ) trick to get it running. Chrome seems to work very well (I'm for standard compliance), but sometimes you just need to know what the user is running in grave detail.
Also, Chrome is very fast. Problem is, some JavaScript code unintentionally depends on the slowness of other browsers to work properly, ie: page loading, iframe loading, placement of stylesheet links and javascript links in page head, etc. These can cause new problems with when functions are really available to interact with page elements. So for now, you really might need to know...
I use this code to make bookmarks for each browser (or display a message for webkit)
if (window.sidebar) {
// Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url,"");
} else if( window.external ) { // IE Favorite
if(window.ActiveXObject) {
//ie
window.external.AddFavorite( url, title);
} else {
//chrome
alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok');
}
} else if(window.opera && window.print) {
// Opera
return true; }
else { //safri
alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok'); }
There might be false positives since opera also has window.chrome object. As a nice solution I use;
var isOpera = !!window.opera || !!window.opr;// Opera 8.0+
var isChrome = !!window.chrome && !isOpera;
This solution almost always works.
However one thing I discovered is that, isChrome returns false in iPad Chrome version 52.0 as window.chrome returns false.
isIE: !!(!window.addEventListener && window.ActiveXObject),
isIE6: typeof document.createElement('DIV').style.maxHeight == "undefined",
isIE7: !!(!window.addEventListener && window.XMLHttpRequest && !document.querySelectorAll),
isIE8: !!(!window.addEventListener && document.querySelectorAll && document.documentMode == 8),
isGecko: navigator.product == 'Gecko',
isOpera: !!window.opera,
isChrome: !!window.chrome,
isWebkit: !!(!window.opera && !navigator.taintEnable && document.evaluate && navigator.product != 'Gecko'),

Categories

Resources