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条回答
Rolldiameter
2楼-- · 2020-01-24 19:33

If you are checking the browser use $.browser. But if you are checking feature support (recommended) then use $.support.

You should NOT use $.browser to enable/disable features on the page. Reason being its not dependable and generally just not recommended.

If you need feature support then I recommend modernizr.

查看更多
祖国的老花朵
3楼-- · 2020-01-24 19:34

For checking Safari I used this:

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

It works correctly.

查看更多
戒情不戒烟
4楼-- · 2020-01-24 19:39
    // Safari uses pre-calculated pixels, so use this feature to detect Safari
    var canva = document.createElement('canvas');
    var ctx = canva.getContext("2d");
    var img = ctx.getImageData(0, 0, 1, 1);
    var pix = img.data;     // byte array, rgba
    var isSafari = (pix[3] != 0);   // alpha in Safari is not zero
查看更多
地球回转人心会变
5楼-- · 2020-01-24 19:40

Using a mix of feature detection and Useragent string:

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

Usage:
if (is_safari) alert('Safari');

Or for Safari only, use this :

if ( /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {alert('Its Safari');}
查看更多
够拽才男人
6楼-- · 2020-01-24 19:40
//Check if Safari
  function isSafari() {
      return /^((?!chrome).)*safari/i.test(navigator.userAgent);
  }
//Check if MAC
     if(navigator.userAgent.indexOf('Mac')>1){
        alert(isSafari());
     }

http://jsfiddle.net/s1o943gb/10/

查看更多
我欲成王,谁敢阻挡
7楼-- · 2020-01-24 19:41

This will determine whether the browser is Safari or not.

if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
    alert(its safari);
}else {
    alert('its not safari');
}
查看更多
登录 后发表回答