Detect Safari using jQuery

2020-01-24 19:12发布

Though both are Webkit based browsers, Safari urlencodes quotation marks in the URL while Chrome does not.

Therefore I need to distinguish between these two in JS.

jQuery's browser detection docs mark "safari" as deprecated.

Is there a better method or do I just stick with the deprecated value for now?

13条回答
男人必须洒脱
2楼-- · 2020-01-24 19:16

The following identifies Safari 3.0+ and distinguishes it from Chrome:

isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)
查看更多
孤傲高冷的网名
3楼-- · 2020-01-24 19:16

A very useful way to fix this is to detect the browsers webkit version and check if it is at least the one we need, else do something else.

Using jQuery it goes like this:

"use strict";

$(document).ready(function() {
    var appVersion                  = navigator.appVersion;
    var webkitVersion_positionStart = appVersion.indexOf("AppleWebKit/") + 12;
    var webkitVersion_positionEnd   = webkitVersion_positionStart + 3;
    var webkitVersion               = appVersion.slice(webkitVersion_positionStart, webkitVersion_positionEnd);
	
    console.log(webkitVersion);

    if (webkitVersion < 537) {
        console.log("webkit outdated.");
    } else {
        console.log("webkit ok.");
    };
});

This provides a safe and permanent fix for dealing with problems with browser's different webkit implementations.

Happy coding!

查看更多
贼婆χ
4楼-- · 2020-01-24 19:17

unfortunately the above examples will also detect android's default browser as Safari, which it is not. I used navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1 && navigator.userAgent.indexOf('Android') == -1

查看更多
该账号已被封号
5楼-- · 2020-01-24 19:25

Generic FUNCTION

 var getBrowseActive = function (browserName) {
   return navigator.userAgent.indexOf(browserName) > -1;
 };
查看更多
冷血范
6楼-- · 2020-01-24 19:27

Apparently the only reliable and accepted solution would be to do feature detection like this:

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;
查看更多
Ridiculous、
7楼-- · 2020-01-24 19:27

The only way I found is check if navigator.userAgent contains iPhone or iPad word

if (navigator.userAgent.toLowerCase().match(/(ipad|iphone)/)) {
    //is safari
}
查看更多
登录 后发表回答