...

View Full Version : simple browser detection



chump2877
10-17-2005, 02:31 PM
This code:


if (navigator.appName == 'Microsoft Internet Explorer') {
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_IE.css">');
}

else if (navigator.appName == 'Opera') {
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_opera.css">');
}

else if (navigator.appName == 'Netscape') {
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos.css">');
}

else {
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_IE.css">');
}

does not seem to effectively serve the appropriate stylesheet to Opera browsers...it works for the other browser types, so why not Opera?

Philip M
10-17-2005, 07:30 PM
Opera is difficult to detect reliably as it often spoofs Internet Explorer.

Have a look at
http://webreference.com/programming/javascript/sniffing/3/
http://javascriptkit.com/javatutors/navigator.shtml

and other pages brought up by Google.
Hope this helps.

Lerura
10-17-2005, 09:23 PM
if (navigator.appName == 'Microsoft Internet Explorer') {
if (navigator.userAgent.indexOf('Opera')==-1){
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_IE.css">');
}else{
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_Opera.css">');
}
}
else if (navigator.appName == 'Netscape') {
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos.css">');
}
else {
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_IE.css">');
}

detects Opera

and if you want to detect Firefox too, use this code:

if (navigator.appName == 'Microsoft Internet Explorer') {
if (navigator.userAgent.indexOf('Opera')==-1){
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_IE.css">');
}else{
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_Opera.css">');
}
}
else if (navigator.appName == 'Netscape') {
if (navigator.userAgent.indexOf('Firefox')==-1){
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos.css">');
}else{
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_FF.css">');
}
}
else {
document.write('<link rel="stylesheet" type="text/css" href="index_with_css_pos_IE.css">');
}


the problem is that Opera's navigator.appName is "Microsoft Internet Explorer"
as well as Firefox's navigator.appName is "Netscape"

there it must look for additional information in navigator.userAgent

chump2877
10-18-2005, 12:17 AM
Thanks, this helps...:-)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum