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

标签 javascript html google-chrome browser-detection

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

如何创建这样的功能?

最佳答案

要检查浏览器是否为 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 检查器并转到控制台选项卡。键入“窗口”并按 Enter。然后您可以查看“窗口对象”的 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。微软拿不定主意!

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

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

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

添加了对 IE Edge 的检查,因为它为 window.chrome 输出 true .. 即使 IE11 为 window 输出 undefined .chrome。感谢 artfulhacker让我们知道这件事!

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

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

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

Opera 的编辑检查,检查 window.opr 不是 undefined 因为现在 Chrome 66 在 window.navigator 中有 OPR。 vendor 。感谢 Frosty ZDaniel Wallman举报!

关于JavaScript:如何判断用户浏览器是否是 Chrome?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4565112/

相关文章:

html - Django : Could not parse the remainder: '{{' from '{{

google-chrome - 当父项具有边框半径且子项具有动画时,隐藏的 CSS 溢出在 chrome 中不起作用

javascript - 没有 Origin header 的 Chrome 扩展 AJAX 请求

javascript - 使用ajax和php将数据显示到html表时遇到问题

javascript - Google Maps API 如何在 iframe 中隐藏 UI

html - 根据条件在 2 列上显示数据

html - bootstrap 3.x 不显示内联的 h4 和图标

html - chrome 中的 anchor 标记无法正常工作?这是 chrome 错误吗?

javascript - 如何在 $(this) 之后选择下一个元素?

javascript - vue-router beforeRouteUpdate 钩子(Hook)无法访问 `this`