使用jQuery.browser区分Chrome和Safari

时间:2010-07-21 21:04:31

标签: jquery safari google-chrome webkit browser-detection

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

7 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:36)

没有 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;

答案 2 :(得分: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/

答案 3 :(得分:2)

/Chrome/.test(navigator.userAgent)

答案 4 :(得分:2)

对于非JQuery用户:

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

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

答案 5 :(得分:0)

window.chrome?$.browser.chrome=!0:($.browser.webkit&&($.browser.safari=!0),$.browser.chrome=!1);

此补丁添加了 $。browser.chrome ,并且还从 $。browser.safari

中排除了Goolge Chrome检测

答案 6 :(得分:0)

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

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

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

            return isSafari;
    },