[JS] 獲取瀏覽器名稱及版本

經navigator.userAgent 進行match updated.

function getBowser() {
    if ((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1) {
            alert('Opera');
    } else if (navigator.userAgent.indexOf("Edg") != -1) {
            alert('Edge');
    } else if (navigator.userAgent.indexOf("Chrome") != -1) {
            alert('Chrome');
    } else if (navigator.userAgent.indexOf("Safari") != -1) {
            alert('Safari');
    } else if (navigator.userAgent.indexOf("Firefox") != -1) {
            alert('Firefox');
    } else if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) //IF IE > 10
    {
            alert('IE');
    } else {
            alert('unknown');
    }
}

下面這個更廣為流傳,但其實無法在 iOS Chrome上作出檢查 當然上面的也只會見到Safari, 因為某種瀏覽器內核的原因,但檢查錯了,總比直接停了來得好

function getExplorerInfo() {
    let explorer = window.navigator.userAgent;
    explorer = explorer.toLowerCase();
    //ie 
    if (explorer.indexOf('msie') >= 0) {
        let ver = explorer.match(/msie ([\d.]+)/)[1] || '';
        return { name: 'IE', version: ver };
    }
    //firefox 
    else if (explorer.indexOf('firefox') >= 0) {
        let ver = explorer.match(/firefox\/([\d.]+)/)[1] || '';
        return { name: 'Firefox', version: ver };
    }
    //Chrome 
    else if (explorer.indexOf('chrome') >= 0) {
        let ver = explorer.match(/chrome\/([\d.]+)/)[1] || '';
        return { name: 'Chrome', version: ver };
    }
    //Opera 
    else if (explorer.indexOf('opera') >= 0) {
        let ver = explorer.match(/opera.([\d.]+)/)[1] || '';
        return { name: 'Opera', version: ver };
    }
    //Safari 
    else if (explorer.indexOf('safari') >= 0) {
        let ver = explorer.match(/version\/([\d.]+)/)[1] || '';
        return { name: 'Safari', version: ver };
    }
    if (explorer.indexOf('edge') >= 0) {
        let ver = explorer.match(/edge\/([\d.]+)/)[1] || '';
        return { name: 'edge', version: ver };
    }
    return { name: '', version: '' };
}