我需要一些函数返回一个布尔值来检查浏览器是否是Chrome。
我如何创建这样的功能?
我需要一些函数返回一个布尔值来检查浏览器是否是Chrome。
我如何创建这样的功能?
当前回答
所有答案都是错的。“Opera”和“Chrome”在所有情况下都是相同的。
(编辑)
下面是正确答案
if (window.chrome && window.chrome.webstore) {
// this is Chrome
}
其他回答
更简短:var is_chrome = /chrome/i。测试(导航器。userAgent);
从Chrome 89(2021年3月)开始,所有以前的答案都已过时。Chrome现在支持用户代理提示。所以现在应该使用:
navigator.userAgentData?.brands?.some(b => b.brand === 'Google Chrome')
或者,如果你不使用Babel:
navigator.userAgentData && navigator.userAgentData.brands && navigator.userAgentData.brands.some(b => b.brand === 'Google Chrome')
对于Chrome 89及以上版本返回true,对于最新的Opera和Edge返回false,对于不支持userAgentData的浏览器返回undefined。
用户可以更改用户代理。尝试在body元素的样式对象中测试webkit的前缀属性
if ("webkitAppearance" in document.body.style) {
// do stuff
}
我发现的最好的解决方案,并在大多数浏览器中给出真或假的答案是:
var isChrome = (navigator.userAgent.indexOf("Chrome") != -1 && navigator.vendor.indexOf("Google Inc") != -1)
使用. indexof而不是.includes使其与浏览器更加兼容。 尽管(或因为)整个重点是使您的代码特定于浏览器,但您需要在大多数(或所有)浏览器中工作的条件。
查询浏览器是否为谷歌Chrome。
var isChrome = navigator.userAgent.includes("Chrome") && navigator.vendor.includes("Google Inc");
console.log(navigator.vendor);
// "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36 "
console.log(navigator.userAgent);
// "Google Inc."