要检查浏览器是否为 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
}
使用示例:http://codepen.io/jonathan/pen/WpQELR
之所以有效,是因为如果您使用 Google Chrome 检查器并转到控制台选项卡。键入“窗口”并按 Enter。然后您可以查看“窗口对象”的 DOM 属性。折叠对象时,您可以查看所有属性,包括“chrome”属性。
您不能再使用严格等于 true 在 IE 中检查 window.chrome。 IE 以前返回undefined,现在返回true。 但你猜怎么着,IE11 现在又返回 undefined。 IE11 还为 window.navigator.vendor 返回一个空字符串 ""。
我希望这会有所帮助!
更新:
感谢Halcyon991 在下方指出,新的 Opera 18+ 也为window.chrome 输出为真。 Opera 18 似乎基于 Chromium 31。所以我添加了一个检查以确保window.navigator.vendor 是:"Google Inc" 而不是"Opera Software ASA"。还要感谢 Ring 和 Adrien 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.chrome 输出 undefined。感谢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.vendor 中有 OPR。感谢Frosty Z 和Daniel Wallman 报告此事!