使用jQuery.browser区分Chrome和Safari

看来, jQuery.browser能够很容易地从1.4版本识别webkit。 但我怎么能用它来区分Chrome浏览器(反之亦然)?

由于Sarfraz没有纠正他的答案(谢谢Sarfraz指出我在正确的方向),我会在这里发布function代码。

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; } 

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

你可以这样做:

 // 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/

 /Chrome/.test(navigator.userAgent) 

另外对于非JQuery用户:

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

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

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

此修补程序添加$ .browser.chrome,并从$ .browser.safari中排除Goolge Chrome检测

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

  isSafari: function () { var isSafari = (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) console.log('IsSafari : ' + isSafari); return isSafari; },