我需要一些函数返回一个布尔值来检查浏览器是否是Chrome。
我如何创建这样的功能?
我需要一些函数返回一个布尔值来检查浏览器是否是Chrome。
我如何创建这样的功能?
当前回答
用户可以更改用户代理。尝试在body元素的样式对象中测试webkit的前缀属性
if ("webkitAppearance" in document.body.style) {
// do stuff
}
其他回答
检查这个:如何检测Safari, Chrome, IE, Firefox和Opera浏览器?
在你的情况下:
var isChrome = (window.chrome.webstore || window.chrome.runtime) && !!window.chrome;
如果你想检测Chrome的渲染引擎(所以不是谷歌Chrome或Chromium中的特定功能),一个简单的选项是:
var isChrome = !!window.chrome;
注意:对于基于Chrome的许多版本的Edge, Opera等也会返回true(感谢@Carrm指出这一点)。避免这种情况是一场持续的战斗(见窗口)。所以你应该问问自己,你是在试图检测渲染引擎(在2020年几乎所有主要的现代浏览器都使用)还是其他一些Chrome(或Chromium?)特定的功能。
你可以跳过!!
更新:请参阅Jonathan的回答,了解处理这个问题的最新方法。下面的答案可能仍然有效,但在其他浏览器中可能会引发一些误报。
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
然而,正如前面提到的,用户代理可能会被欺骗,所以在处理这些问题时,最好使用特征检测(例如Modernizer),正如其他答案所提到的。
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嗅探是不好的做法,尽可能使用特征检测。
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, ' '));