javascript navigator.userAgent

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4986993/
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-10-25 15:34:05  来源:igfitidea点击:

navigator.userAgent

javascript

提问by Cam

I am trying to detect if the browser is Safari. If so, only then do something. In all other browsers, do something else:

我正在尝试检测浏览器是否为 Safari。如果是这样,那么只有做点什么。在所有其他浏览器中,执行其他操作:

if ( navigator.userAgent.toLowerCase().indexOf('safari') == -1) {
    //if safari execute some function
} else {
   // if other browsers execute other function
}

However, I guess I am not using the right approach because it's not working. :P

但是,我想我没有使用正确的方法,因为它不起作用。:P

采纳答案by jmort253

Quirksmode has a Browser Detection Scriptthat you can use to detect the different browsers that are being used and then perform different actions based on that browser type.

Quirksmode 有一个浏览器检测脚本,您可以使用它来检测正在使用的不同浏览器,然后根据该浏览器类型执行不同的操作。

Under the hood, it's essentially using the same technique that you are trying to use.

在幕后,它本质上使用与您尝试使用的技术相同的技术。

In your example, you actually are close. A quick fix is to just change the ==to !=and voila, your script should work!

在您的示例中,您实际上很接近。一个快速的解决方法是更改==to!=并且瞧,您的脚本应该可以工作!

However, I am running Chrome, not Safari! Yet, in my user agent string, I see the following:

但是,我运行的是 Chrome,而不是 Safari!然而,在我的用户代理字符串中,我看到以下内容:

"Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.10 
      (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10"

The word "Safari" appears in my userAgent String, which means that, using your script, my browser would be treated as if it were Safari!

“Safari”一词出现在我的 userAgent 字符串中,这意味着,使用您的脚本,我的浏览器将被视为 Safari!

回答by DejanR

if(typeof navigator.vendor!='undefined') &&
   navigator.vendor.toLowerCase().indexOf('apple')!=-1){
    ...
}

回答by bdanin

I ended up using

我最终使用

var isSafari = navigator.userAgent.match(/safari/i) != null && navigator.userAgent.match(/chrome/i) == null;

if(isSafari){
    // code here
  }