browser identification - javascript

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).

Related

How can I detect iOS6 device using feature detection

Is there any generic way to detect iOS6 device using feature detection.
I think the best way is always to parse the user agent string but you can detect the Safari version introduced with iOS 6 using a previously unsupported feature (see this article for a more complete list, I'll provide just one example).
Basically you have to mimic the same technique used by modernizr, with this piece of code you'll check if the <input> type file is supported, if it is then you're running on Safari with iOS 6 or greater. Of course just using features you can't be sure that the user isn't using another browser (that's why I prefer the user agent string if you have to detect the OS version). For a comparison see this post here on SO.
function isNewVersion() {
var elem = document.createElement("input");
elem.setAttribute("type", "file");
return elem.type !== "text";
}
You could check the FileReader API, but of course this'll match many modern desktop browsers, too (I'm not sure if that's going to cause you some problems, but I doubt it):
var iOS6 = false;
if(window.FileReader)
{
iOS6 = true;
}

Javascript detection not working anymore

After this weekend my Wicket application cannot correctly detect javascript anymore. It doesn't work on my webhoster, on my local machine and I tested it also on another computer.
My detection script:
WebClientInfo clientInfo = (WebClientInfo)WebSession.get().getClientInfo();
if(!clientInfo.getProperties().isJavaEnabled()){
System.out.println("not enabled!");
WebSession.get().setClientInfo(null);
}
plus this in the application class:
getRequestCycleSettings().setGatherExtendedBrowserInfo(true);
I also created a wicket app from scratch, same result, no javascript detection.
While writing this I checked it in the Internet Explorer. Works fine with IE 8 + 9. Doesn't work with FF 11.0. Wicket version is 1.5.5.
Anyone can confirm this behavior? (possible JIRA-worthy...)
UPDATE: I found the cause of this behavior. isJavaEnabled checks if Java (not Javascript) is enabled. Firefox (silently) blocked the Java plugin on April 2nd, therefore no javaEnabled property set: https://addons.mozilla.org/en-US/firefox/blocked/p80. Cumbersome.
Likely this never worked, and the fact that it seemed to was dumb luck.
Looking at the javadocs for ClientProperties.isJavaEnabled(), it returns the client's navigator.javaEnabled property, which reflects whether Java is enabled, not JavaScript.
Java != JavaScript.
An alternative is to use the 'user agent' string:
public boolean javascriptSupported() {
WebRequest webRequest = (WebRequest) getRequest();
String userAgent = webRequest.getHeader("User-Agent");
if (userAgent == null || userAgent.startsWith("Googlebot")) {
return false;
}
return true;
}
I have used this to fallback on AjaxLazyLoadPanel for search engines, although you would need to expand on the list of user-agents above.
There is also WebRequest.isAjax(), which might be useful too, as it is used to determine the RedirectPolicy used, and thus, the behaviour of Wicket when Javascript is not present.

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