JavaScript:如何判断用户浏览器是否是 Chrome?

新手上路,请多包涵

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

如何创建这样的功能?

原文由 Rella 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

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

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

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

原文由 Rion Williams 发布,翻译遵循 CC BY-SA 3.0 许可协议

要检查浏览器是否为 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("Edg") > -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
}

使用示例: https ://codepen.io/jonathan/pen/RwQXZxJ?editors=1111

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

您不能再使用严格等于 true 在 IE 中检查 window.chrome 。 IE 过去返回 undefined ,现在它返回 true但是你猜怎么着,IE11 现在再次返回 undefined。 IE11 还为 — 返回一个空字符串 "" window.navigator.vendor

更新:

感谢 Halcyon991 在下面指出,新的 Opera 18+ 也为 window.chrome 输出 true。看起来 Opera 18 是基于 Chromium 31 的。所以我添加了一个检查以确保 window.navigator.vendor 是: "Google Inc" 而不是 "Opera Software ASA" 。还要感谢 RingAdrien Be 提醒有关 Chrome 33 不再返回 true … window.chrome 现在检查是否不为空。但是请密切注意 IE11,我添加了对 undefined 的检查,因为 IE11 现在输出 undefined ,就像它在首次发布时所做的那样……然后在一些更新构建后它输出到 true .. 现在最近的更新版本再次输出 undefined 。微软拿不定主意!

更新 7/24/2015 - 添加 Opera 检查

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

更新 10/13/2015 - 添加 IE 检查

Added check for IE Edge due to it true for window.chrome .. even though IE11 outputs undefined for window.chrome .感谢 artfulhacker 让我们知道这件事!

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

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

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

Edited check for Opera, checking window.opr is not undefined since now Chrome 66 has OPR in window.navigator.vendor .感谢 Frosty ZDaniel Wallman 报告此事!

原文由 Jonathan Marzullo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题