使用jQuery检测Safari

And*_*eKR 109 javascript jquery browser-detection

虽然两者都是基于Webkit的浏览器,但是在URL中的Safari urlencodes引号却没有.

因此我需要在JS中区分这两者.

jQuery的浏览器检测文档将"safari"标记为已弃用.

有没有更好的方法,或者我现在只是坚持使用已弃用的值?

Pan*_*al. 330

使用feature detectionUseragent字符串的混合:

    var is_opera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    var is_Edge = navigator.userAgent.indexOf("Edge") > -1;
    var is_chrome = !!window.chrome && !is_opera && !is_Edge;
    var is_explorer= typeof document !== 'undefined' && !!document.documentMode && !is_Edge;
    var is_firefox = typeof window.InstallTrigger !== 'undefined';
    var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
Run Code Online (Sandbox Code Playgroud)

用法:
if (is_safari) alert('Safari');

或者仅限Safari,请使用:

if ( /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {alert('Its Safari');}
Run Code Online (Sandbox Code Playgroud)

  • Chrome/Windows将报告为Safari:`(Mozilla/5.0(Windows NT 6.1; WOW64)AppleWebKit/537.36(KHTML,如Gecko)Chrome/36.0.1985.125 Safari/537.36) (15认同)
  • is_explorer =(navigator.userAgent.indexOf('MSIE')!== -1 || navigator.appVersion.indexOf('Trident /')> 0)也支持IE11 >>> http://stackoverflow.com/a /二百○四万九千九百八十六分之二千二百二十四万二千五百二十八 (6认同)
  • 对于具有副作用的特征检测,具有48票对5票的比率,显然这是推荐的解决方案.:)让它接受答案. (3认同)

小智 75

以下标识Safari 3.0+并将其与Chrome区分开来:

isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)
Run Code Online (Sandbox Code Playgroud)

  • 当其他人都没有时,这个对我有用,谢谢. (10认同)

小智 10

不幸的是,上面的例子也会将android的默认浏览器检测为Safari,但事实并非如此.我用了 navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1 && navigator.userAgent.indexOf('Android') == -1


Fla*_*sta 7

为了检查Safari我使用了这个:

$.browser.safari = ($.browser.webkit && !(/chrome/.test(navigator.userAgent.toLowerCase())));
if ($.browser.safari) {
    alert('this is safari');
}
Run Code Online (Sandbox Code Playgroud)

它工作正常.