AKB
AKB

Reputation: 5938

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?

Upvotes: 0

Views: 391

Answers (3)

E.R.Rider
E.R.Rider

Reputation: 74

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

Upvotes: 0

Mnebuerquo
Mnebuerquo

Reputation: 5949

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.

Upvotes: 0

Callie J
Callie J

Reputation: 31296

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.

Upvotes: 2

Related Questions