使用 jQuery 检测 Safari

IT技术 javascript jquery browser-detection
2021-02-19 04:02:45

尽管两者都是基于 Webkit 的浏览器,但 Safari 会对 URL 中的引号进行 urlencode,而 Chrome 则不会。

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

jQuery 的浏览器检测文档将“safari”标记为已弃用。

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

6个回答

使用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);

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

或仅适用于 Safari,请使用以下命令:

if ( /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {alert('Its Safari');}
Android webview 也会说 Safari,这是不正确的
2021-04-17 04:02:45
is_explorer = (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) 也支持IE11 >>> stackoverflow.com/a/22242528/2049986
2021-04-17 04:02:45
作为此类事情的脆弱性的一个示例,此代码未检测到 Internet Explorer 11,因为 UA 字符串已更改。请参阅msdn.microsoft.com/en-us/library/ie/hh869301%28v=vs.85%29.aspx
2021-04-28 04:02:45
对于带有副作用的特征检测,48 票对 5 票的比例,显然这是推荐的解决方案。:) 让它接受答案。
2021-05-09 04:02:45
Chrome/Windows 将报告为 Safari: (Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36)
2021-05-14 04:02:45

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

isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)
这就是事情。TNX!
2021-04-28 04:02:45

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

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

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

它工作正常。

显然,唯一可靠且可接受的解决方案是像这样进行特征检测:

browser_treats_urls_like_safari_does = false;
var last_location_hash = location.hash;
location.hash = '"blah"';
if (location.hash == '#%22blah%22')
    browser_treats_urls_like_safari_does = true;
location.hash = last_location_hash;
特征检测是要走的路,但有一种更好的方法,它没有任何副作用。您的代码段可能会干扰依赖哈希更改事件的其他脚本。我已将该问题标记为this的副本我已经在 Safari 3.0 - 5.1.3(Mac 和 Windows)中创建并测试了该方法。这是一个单线:)
2021-05-02 04:02:45
不错的技巧,但不幸的是它不起作用。由于 location.hash 处理字符串的方式,等式 (location.hash == '#%22blah%22') 将不起作用。:/
2021-05-14 04:02:45