2017-10-11 55 views
0

我已經把下面的代碼在我的網站來檢查我該瀏覽器:JavaScript的瀏覽器檢測的作品,但顯示爲「不確定」後

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()); 

的代碼工作正常。當我在Google Chrome中時,它顯示的是名稱,但在瀏覽器名稱旁邊顯示「未定義」一詞。

+0

返回瀏覽器的名稱 –

+0

@SagarV你這是什麼意思的代碼? –

+0

'myFunction'沒有return語句...所以,因爲javascript是這樣寫的,所以這與'return undefined'完全相同[ –

回答

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());

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());

相關問題