如何捕获用于访问网页的浏览器?

时间:2018-06-06 16:21:54

标签: javascript html modal-dialog

假设我正在编写一个包含两个框的简单网页,名称宠物名称。如果最终用户使用任何给定的Web浏览器浏览到此站点,我将如何显示弹出通知以显示用户的浏览器?

例如,如果我使用Microsoft Edge或IE 11浏览到此页面,我将如何立即显示一个对话框,其中包含以下内容:

“您正在使用IE11”或“您正在使用Microsoft Edge”?

2 个答案:

答案 0 :(得分:0)

最接近你想要的东西是通过前端的浏览器“用户代理字符串”。

类似:Getting the User Agent with JavaScript

这里还有一个库,可以将值传递给更有用的状态。 https://github.com/faisalman/ua-parser-js

答案 1 :(得分:0)

还有很多关于如何检测浏览器版本的Stack Overflow问题:How can you detect the version of a browser?

拥有浏览器版本后,alert可以显示包含该信息的对话框,而不是使用上面接受的答案中的控制台日志。

更新:在我关联的页面下方是可在Edge和IE上运行的浏览器检测。 Credit to Brandon

navigator.browserSpecs = (function(){
    var ua = navigator.userAgent, tem, 
        M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return {name:'IE',version:(tem[1] || '')};
    }
    if(M[1]=== 'Chrome'){
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem != null) return {name:tem[1].replace('OPR', 'Opera'),version:tem[2]};
    }
    M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem = ua.match(/version\/(\d+)/i))!= null)
        M.splice(1, 1, tem[1]);
    return {name:M[0], version:M[1]};
})();
相关问题