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

我如何创建这样的功能?


当前回答

我发现的最好的解决方案,并在大多数浏览器中给出真或假的答案是:

var isChrome = (navigator.userAgent.indexOf("Chrome") != -1 && navigator.vendor.indexOf("Google Inc") != -1)

使用. indexof而不是.includes使其与浏览器更加兼容。 尽管(或因为)整个重点是使您的代码特定于浏览器,但您需要在大多数(或所有)浏览器中工作的条件。

其他回答

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

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

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

Var is_chrome = /chrome/。~ . test(navigator.userAgent.toLowerCase()) 这是一个12年前写的老答案;从现在起(即:, 2022年8月)


更新(2022年8月):

现在,使用用户代理(用户代理嗅探)进行浏览器检测通常不是一个好主意。特征检测应该是正确的方法。

参考:使用用户代理进行浏览器检测

然而,如果你仍然希望这样做,使用第三方库,如

var parser = new UAParser(); var result = parser.getResult(); console.log(result.browser);// {name: "Chrome", version: "104.0.0.0", "major": "104"} console.log(result.device); // {model: undefined, type: undefined, vendor: undefined} console.log(result.os); // {name: "Windows", version: "10"} console.log(result.engine); // {name: "Blink", version: "104.0.0.0"} console.log(result.cpu); // {"architecture": "amd64"} <script src="https://cdnjs.cloudflare.com/ajax/libs/UAParser.js/1.0.2/ua-parser.min.js"> </script>

上面的代码段使用了ua-parser-js库

CDN - https://cdnjs.com/lies/uaparser.js - npm - https://www.npmjs.com/package/ua-parser-js

附注:请注意UA嗅探是不好的做法,尽可能使用特征检测。

更新:请参阅Jonathan的回答,了解处理这个问题的最新方法。下面的答案可能仍然有效,但在其他浏览器中可能会引发一些误报。

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);

然而,正如前面提到的,用户代理可能会被欺骗,所以在处理这些问题时,最好使用特征检测(例如Modernizer),正如其他答案所提到的。

现在你可以使用navigator.userAgent.includes(“Chrome”)