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

我如何创建这样的功能?


当前回答

更简短:var is_chrome = /chrome/i。测试(导航器。userAgent);

其他回答

所有答案都是错的。“Opera”和“Chrome”在所有情况下都是相同的。

(编辑)

下面是正确答案

if (window.chrome && window.chrome.webstore) {
    // this is Chrome
}

如果你想检测Chrome的渲染引擎(所以不是谷歌Chrome或Chromium中的特定功能),一个简单的选项是:

var isChrome = !!window.chrome;

注意:对于基于Chrome的许多版本的Edge, Opera等也会返回true(感谢@Carrm指出这一点)。避免这种情况是一场持续的战斗(见窗口)。所以你应该问问自己,你是在试图检测渲染引擎(在2020年几乎所有主要的现代浏览器都使用)还是其他一些Chrome(或Chromium?)特定的功能。

你可以跳过!!

在Mac上的Chrome上为我工作。似乎比上面所有的都更简单或更可靠(如果userAgent字符串测试)。

        var isChrome = false;
        if (window.chrome && !window.opr){
            isChrome = true;
        }
        console.log(isChrome);

从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。

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, ' '));