我一直在尝试不同的脚本,我发现一个适用于除 Chrome 之外的所有脚本...这是我一直在使用的用于区分 .CSS 文件的代码。我尝试将浏览器名称设置为“Chrome”,但这不起作用。
if (browser == 'Firefox') {
document.write('<link rel="stylesheet" href="../component/fireFoxdefault.css" />');
}
if (browser == 'Safari') {
document.write('<'+'link rel="stylesheet" href="../component/default.css" />');
}
使用以下方法检测铬:
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
来源:http://davidwalsh.name/detecting-google-chrome-javascript
更新(2015-07-20):
上述解决方案并不总是有效。可以在这个答案中找到更可靠的解决方案(见下文)。话虽这么说,我会 避免浏览器检测并改为使用功能检测:
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
您可以包含专门用于 chrome 的 css 文件,如下所示:
if (isChrome) {
document.write('<'+'link rel="stylesheet" href="../component/chromeDefault.css" />');
}
更新(2014-07-29):
@gillesc 有一个更优雅的检测 Chrome 的建议,他在下面的评论中发布了该建议,也可以在这个 question 上查看。
var isChrome = !!window.chrome
这里有两种简单的方法,一种使用indexOf,一种使用test:
// first method
function check_chrome_ua() {
var ua = navigator.userAgent.toLowerCase();
var is_chrome = /chrome/.test(ua);
return is_chrome;
}
// second method */
function check_chrome_ua2() {
var ua = navigator.userAgent.toLowerCase();
var is_chrome = ua.indexOf("applewebkit/") != -1 && ua.indexOf("khtml") > - 1;
return is_chrome;
}
alert(check_chrome_ua()); // false or true
alert(check_chrome_ua2()); // false or true
使用这两个布尔函数之一检查chrome是否正在使用后,您可以实现更改样式表的方法。
iOS 上的 Chrome 更新:Chrome 38(在 iOS 8.1 上测试)在
!!window.chrome
上返回 false。要解决此问题,您可以使用:
function isChrome(){
var windowChrome = !!window.chrome;
if(!windowChrome){
// Chrome iOS specific test
var pattern = /crios/i;
return pattern.test(window.navigator.userAgent);
}else{
return windowChrome;
}
}
谷歌参考关于此事
如果您遇到 TypeScript 错误或警告。也许像下面这样:
Property 'chrome' does not exist on type 'Window & typeof globalThis'
您可以通过执行以下操作来检查
"chrome"
是否是窗口对象的键:
if("chrome" in window)
在我的代码中,我创建了一个函数:
function isChrome(){
return "chrome" in window;
}
var userAgent = navigator.userAgent.toLowerCase();
$.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
// Is this a version of Chrome?
if($.browser.chrome){
userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
userAgent = userAgent.substring(0,userAgent.indexOf('.'));
$.browser.version = userAgent;
// If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
$.browser.safari = false;
}
// Is this a version of Safari?
if($.browser.safari){
userAgent = userAgent.substring(userAgent.indexOf('safari/') +7);
userAgent = userAgent.substring(0,userAgent.indexOf('.'));
$.browser.version = userAgent;
}