JavaScript:如何确定用户浏览器是否为 Chrome?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4565112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:59:26  来源:igfitidea点击:

JavaScript: How to find out if the user browser is Chrome?

javascripthtmlgoogle-chromebrowser-detection

提问by Rella

I need some function returning a boolean value to check if the browser is Chrome.

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

How do I create such functionality?

我如何创建这样的功能?

采纳答案by Rion Williams

Update: Please see Jonathan's answerfor an updated way to handle this. The answer below may still work, but it could likely trigger some false positives in other browsers.

更新:请参阅乔纳森的回答以获取处理此问题的更新方法。下面的答案可能仍然有效,但它可能会在其他浏览器中触发一些误报。

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

However, as mentioned User Agents can be spoofed so it is always best to use feature-detection (e.g. Modernizer) when handling these issues, as other answers mention.

但是,如前所述,用户代理可能会被欺骗,因此在处理这些问题时,最好始终使用特征检测(例如Modernizer),正如其他答案所述。

回答by Jonathan Marzullo

To check if browser is Google Chrome, try this:

要检查浏览器是否为Google Chrome,请尝试以下操作:

// please note, 
// that IE11 now returns undefined again for window.chrome
// and new Opera 30 outputs true for window.chrome
// but needs to check if window.opr is not undefined
// and new IE Edge outputs to true now for window.chrome
// and if not iOS Chrome check
// so use the below updated condition
var isChromium = window.chrome;
var winNav = window.navigator;
var vendorName = winNav.vendor;
var isOpera = typeof window.opr !== "undefined";
var isIEedge = winNav.userAgent.indexOf("Edge") > -1;
var isIOSChrome = winNav.userAgent.match("CriOS");

if (isIOSChrome) {
   // is Google Chrome on IOS
} else if(
  isChromium !== null &&
  typeof isChromium !== "undefined" &&
  vendorName === "Google Inc." &&
  isOpera === false &&
  isIEedge === false
) {
   // is Google Chrome
} else { 
   // not Google Chrome 
}

Example of use: http://codepen.io/jonathan/pen/WpQELR

使用示例:http: //codepen.io/jonathan/pen/WpQELR

The reason this works is because if you use the Google Chrome inspector and go to the console tab. Type 'window' and press enter. Then you be able to view the DOM properties for the 'window object'. When you collapse the object you can view all the properties, including the 'chrome' property.

这样做的原因是因为如果您使用 Google Chrome 检查器并转到控制台选项卡。输入“窗口”并按回车键。然后您就可以查看“窗口对象”的 DOM 属性。当您折叠对象时,您可以查看所有属性,包括“chrome”属性。

You can't use strictly equals true anymore to check in IE for window.chrome. IE used to return undefined, now it returns true. But guess what, IE11 now returns undefined again.IE11 also returns a empty string ""for window.navigator.vendor.

您不能再使用严格等于 true 在 IE 中检查window.chrome. IE 曾经返回undefined,现在它返回true但是你猜怎么着,IE11 现在再次返回 undefined 。IE11 还""window.navigator.vendor.

I hope this helps!

我希望这有帮助!

UPDATE:

更新:

Thank you to Halcyon991for pointing out below, that the new Opera 18+ also outputs to true for window.chrome. Looks like Opera 18is based on Chromium 31. So I added a check to make sure the window.navigator.vendoris: "Google Inc"and not is "Opera Software ASA". Also thanks to Ringand Adrien Befor the heads up about Chrome 33 not returning true anymore... window.chromenow checks if not null. But play close attention to IE11, I added the check back for undefinedsince IE11 now outputs undefined, like it did when first released.. then after some update builds it outputted to true.. now recent update build is outputting undefinedagain. Microsoft can't make up it's mind!

感谢Halcyon991在下面指出,新的 Opera 18+ 也为window.chrome. 看起来Opera 18是基于Chromium 31 的。所以我添加了一个检查以确保window.navigator.vendoris:"Google Inc"和 not is "Opera Software ASA"。还要感谢RingAdrien Be关于 Chrome 33 不再返回 true 的提醒……window.chrome现在检查是否不为 null。但是,玩密切关注IE11,我增加了支票寄回undefined,因为IE11现在输出undefined,就像它第一次发布的时候..一些更新,然后建立后,输出到true..现在最新更新打造的是输出undefined一次。微软拿不定主意!

UPDATE7/24/2015 - addition for Opera check

2015 年 7 月 24 日更新- Opera 检查的添加

Opera 30 was just released. It no longer outputs window.opera. And also window.chromeoutputs to true in the new Opera 30. So you must check if OPRis in the userAgent. I updated my condition above to account for this new change in Opera 30, since it uses same render engine as Google Chrome.

Opera 30 刚刚发布。它不再输出window.opera. 并且window.chrome在新的 Opera 30 中也输出为 true。因此您必须检查OPR是否在userAgent 中。我更新了上面的条件以说明 Opera 30 中的这一新变化,因为它使用与 Google Chrome 相同的渲染引擎。

UPDATE10/13/2015 - addition for IE check

2015 年 10 月 13 日更新- 添加 IE 检查

Added check for IE Edge due to it outputting truefor window.chrome.. even though IE11 outputs undefinedfor window.chrome. Thanks to artfulhackerfor letting us know about this!

添加了对 IE Edge 的检查,因为它输出truewindow.chrome.. 即使 IE11 输出undefinedwindow.chrome. 感谢artfulhacker让我们知道这一点!

UPDATE2/5/2016 - addition for iOS Chrome check

2016 年 2 月 5 日更新- 添加 iOS Chrome 检查

Added check for iOS Chrome check CriOSdue to it outputting truefor Chrome on iOS. Thanks to xinthosefor letting us know about this!

添加了对 iOS Chrome 检查的检查,CriOS因为它true在 iOS 上为 Chrome输出。感谢xinthose让我们知道这件事!

UPDATE4/18/2018 - change for Opera check

2018 年 4 月 18 日更新- Opera 检查的更改

Edited check for Opera, checking window.opris not undefinedsince now Chrome 66 has OPRin window.navigator.vendor. Thanks to Frosty Zand Daniel Wallmanfor reporting this!

编辑了对 Opera 的检查window.oprundefined因为现在 Chrome 66 已OPRwindow.navigator.vendor. 感谢Frosty ZDaniel Wallman报告此事!

回答by The Big Lebowski

even shorter: var is_chrome = /chrome/i.test( navigator.userAgent );

甚至更短: var is_chrome = /chrome/i.test( navigator.userAgent );

回答by Drew Noakes

A much simpler solution is just to use:

一个更简单的解决方案是使用:

var isChrome = !!window.chrome;

The !!just converts the object to a boolean value. In non-Chrome browsers, this property will be undefined, which is not truthy.

!!刚刚转换的对象为布尔值。在非 Chrome 浏览器中,此属性将为undefined,这不是真的。

Note this also returns true for versions of Edge that are based on Chrome (thanks @Carrm for pointing this out).

请注意,对于基于 Chrome 的 Edge 版本,这也会返回 true(感谢 @Carrm 指出这一点)。

回答by Josef Je?ek

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

回答by naveen

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

回答by MrOodles

You may also want the specific version of Chrome:

您可能还需要特定版本的 Chrome:

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

Apologies to The Big Lebowski for using his answer within mine.

向 The Big Lebowski 道歉,因为他在我的回答中使用了他的回答。

回答by magg89

You can use:

您可以使用:

navigator.userAgent.indexOf("Chrome") != -1

It is working on v.71

它正在处理 v.71

回答by yurin

Works for me on Chrome on Mac. Seems to be or simpler or more reliable (in case userAgent string tested) than all above.

在 Mac 上的 Chrome 上对我有用。似乎比以上所有更简单或更可靠(如果测试了 userAgent 字符串)。

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

回答by guest271314

User could change user agent . Try testing for webkitprefixed property in styleobject of bodyelement

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

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