使用浏览器进行浏览器检测

Browser detection using Chrome

本文关键字:浏览器 检测      更新时间:2023-09-26

我有这个代码:

<body onload="detect(navigator.appName)">
<h2 id=alert>This tutorial is for Google Chrome users,
why would you want to read it?</h2>
</body>
<script>
function detect(x){
    alert(x)
    if (x != "Chrome"){
        document.getElementById("alert").style.display = '';
    }
}
</script>

问题是,每当我使用谷歌浏览器打开页面时,它都会返回"Netscape"。有解决方法吗?

网页

在 chrome 上,这就是navigator.appName会给你的:

网景

如果您解析用户代理,这将容易得多

if ( ! /(Chrome)/i.test(navigator.userAgent)) {
    document.getElementById("alert").style.display = '';
}

但我不得不说,如果您只向使用 Chrome 的人展示您的教程,那么您就错过了互联网的重点。

试试jQuery的浏览器函数 http://api.jquery.com/jQuery.browser/。这是经过测试的,也是真实的。