31

从 1.4 开始, jQuery.browser似乎能够相当容易地识别 webkit。但是如何使用它来区分 Chrome 和 Safari(反之亦然)?

4

7 回答 7

38

由于 Sarfraz 没有更正他的答案(感谢 Sarfraz 为我指出正确的方向),我将在此处发布功能代码。

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('version/') +8);
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
  $.browser.version = userAgent;
}
于 2010-07-29T16:20:24.430 回答
37

没有jQuery

isChrome = function() { 
  return /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
}
isSafari = function() {
  return /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
}

使用jQuery

(以下不适用于 jQuery 1.9 及更高版本,因为jQuery.browser已从 jQuery 中删除。请参阅http://api.jquery.com/jQuery.browser/

$.browser.chrome = $.browser.webkit && !!window.chrome;
$.browser.safari = $.browser.webkit && !window.chrome;
于 2011-08-08T07:13:40.623 回答
2

你可以这样做:

// Is this a version of Chrome?
if($.browser.chrome){
  userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
  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('.'));
  version = userAgent;
}

http://api.jquery.com/jQuery.browser/

于 2010-07-21T21:07:54.180 回答
2
/Chrome/.test(navigator.userAgent)
于 2010-07-21T21:14:31.777 回答
2

也适用于非 JQuery 用户:

    navigator.userAgent.indexOf('WebKit') + 1 ? 
       ((navigator.vendor || '').indexOf('Apple') + 1 ? /* Safari */ : /* Chrome */)
    : /* not Webkit */

http://jsfiddle.net/HtWag/13/

于 2012-04-24T11:40:23.850 回答
1

您也可以尝试使用这种方法,它对我有用。

    isSafari: function () 
    {
            var isSafari = (navigator.userAgent.indexOf('Safari') != -1
                        && navigator.userAgent.indexOf('Chrome') == -1)

            console.log('IsSafari : ' + isSafari);

            return isSafari;
    },
于 2015-02-12T07:13:05.570 回答
0
window.chrome?$.browser.chrome=!0:($.browser.webkit&&($.browser.safari=!0),$.browser.chrome=!1);

此补丁添加了$.browser.chrome并从$.browser.safari中排除了 Goolge Chrome 检测

于 2012-03-26T07:39:50.183 回答