我已将以下代码放入我的网站,以检查我所在的浏览器:
function myFunction() {
if ((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1) {
document.write('Opera');
} else if (navigator.userAgent.indexOf("Chrome") != -1) {
document.write('Google Chrome');
} else if (navigator.userAgent.indexOf("Safari") != -1) {
document.write('Safari');
} else if (navigator.userAgent.indexOf("Firefox") != -1) {
document.write('Firefox');
} else if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) { //IF IE > 10
document.write('IE (Internet Explorer)');
} else {
document.write('Browser Undefined');
}
}
document.write(myFunction());
代码工作正常。当我在谷歌浏览器中时,它显示的是名称,但在浏览器名称旁边显示“未定义”一词。
答案 0 :(得分:1)
function myFunction() {
if ((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1) {
return 'Opera'
} else if (navigator.userAgent.indexOf("Chrome") != -1) {
return 'chome'
} else if (navigator.userAgent.indexOf("Safari") != -1) {
return 'Safar'
} else if (navigator.userAgent.indexOf("Firefox") != -1) {
return 'Foxy'
} else if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) { //IF IE > 10
return 'MIS'
} else {
return document.write('Browser Undefined');
}
}
document.write(myFunction());

答案 1 :(得分:0)
您可以编写类似
的代码
function myFunction() {
var browser = "";
if ((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1) {
browser = 'Opera'
} else if (navigator.userAgent.indexOf("Chrome") != -1) {
browser = 'chrome'
} else if (navigator.userAgent.indexOf("Safari") != -1) {
browser = 'Safar'
} else if (navigator.userAgent.indexOf("Firefox") != -1) {
browser = 'Foxy'
} else if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) { //IF IE > 10
browser = 'MIS'
} else {
browser = 'Browser Undefined';
}
return browser;
}
document.write(myFunction());