我需要一些函数返回一个布尔值来检查浏览器是否是Chrome。

我如何创建这样的功能?


当前回答

查询浏览器是否为谷歌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."

其他回答

如果你有勇气,你可以尝试浏览器嗅探,得到一个版本:

var ua = navigator.userAgent;
if(/chrome/i.test(ua)) {
    var uaArray = ua.split(' ')
    ,   version = uaArray[uaArray.length - 2].substr(7);
}

这个检测到的版本可能是Chrome版本,或者Edge版本,或者其他版本。浏览器插件可以很容易地改变userAgent、平台和其他东西,所以不建议这样做。

向绿脚趾向我道歉,我用了他的答案。

查询浏览器是否为谷歌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."

console.log(JSON.stringify({ isAndroid: /Android/.test(navigator.userAgent), isCordova: !!window.cordova, isEdge: /Edge/.test(navigator.userAgent), isFirefox: /Firefox/.test(navigator.userAgent), isChrome: /Google Inc/.test(navigator.vendor), isChromeIOS: /CriOS/.test(navigator.userAgent), isChromiumBased: !!window.chrome && !/Edge/.test(navigator.userAgent), isIE: /Trident/.test(navigator.userAgent), isIOS: /(iPhone|iPad|iPod)/.test(navigator.platform), isOpera: /OPR/.test(navigator.userAgent), isSafari: /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent), isTouchScreen: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch, isWebComponentsSupported: 'registerElement' in document && 'import' in document.createElement('link') && 'content' in document.createElement('template') }, null, ' '));

var is_chrome = browseris.chrome

或者查看浏览器:

browseris.firefox
browseris.ie
browseris.safari

此外,你可以像browseris一样检查版本。Chrome7up等等。

检查browseris对象中的所有现有信息

用户可以更改用户代理。尝试在body元素的样式对象中测试webkit的前缀属性

if ("webkitAppearance" in document.body.style) {
  // do stuff
}