【发布时间】:2018-09-16 02:59:47
【问题描述】:
我的网站上有一个聊天机器人,它需要最新版本的浏览器才能完美运行,所以我需要向用户显示一条消息,说“请将您的浏览器更新到最新版本”。我不想使用第三方插件。如果用户使用此 js 代码使用不受支持的浏览器版本,我如何显示 div
HTML
<div id="printVer"></div>
JS
navigator.sayswho= (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 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
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 M.join(' ');
})();
document.getElementById('printVer').innerHTML=navigator.sayswho
【问题讨论】:
-
userAgent “嗅探”不被认为是准确的 - 首选选项是使用特征检测......想想自己,我使用什么“新”功能......检查它们......做适当的未检测到时的操作
-
了解一下为什么 useragent 是一个谬论:modernizr.com/docs/#what-is-feature-detection
-
在浏览器中更改用户代理也很容易。当一个全新的“超级浏览器”出现时会发生什么,您没有考虑过但您的代码可以使用,但您的页面愚蠢地显示“更新到最新版本” - 但我有“最新”版本,你打算每周更新你的代码吗?
-
@freedomn-m 我们主要考虑 Chrome(60 以上)、firefox(50 以上)和 IE(11)。使用 modenizr 检测版本和显示消息是否容易?我在问的 modenizr 很新。谢谢
-
不,你错过了整个概念。您是说“这只适用于浏览器 x vn,所以我需要检查 x vn”-实际上您的代码“仅适用于浏览器 x vn 具有功能 A”-因此您需要“检查功能 A”然后它是什么浏览器并不重要,因为它具有您想要/需要的功能。
标签: javascript jquery html browser browser-detection