182
votes

How to detect Safari browser using JavaScript? I have tried code below and it detects not only Safari but also Chrome browser.

function IsSafari() {

  var is_safari = navigator.userAgent.toLowerCase().indexOf('safari/') > -1;
  return is_safari;

}
21
Some of JS code related to file submitting works deferentially for Safari, for Chrome works fine.Tomas
You should almost certainly be testing for whatever differences in the APIs there are. There are other WebKit based browsers beyond Safari and Chrome.Quentin
There are many reasons one might wish to detect the browser. For example, as of this writing certain aspects of the SVG engine such as filters are broken in Safari, but working in Chrome.Paul Legato
Sometimes you just can't fix bug because you can't reproduce it(I don't have access to Mac). I fixed problem on Midori(some BlobBuilder/Blob issue for sendAsBinary shim), but client says there is still an issue with file upload, so the best thing i can think of is just to remove Safari support and use iframes for it(as for old IE)llamerr

21 Answers

122
votes

You can easily use index of Chrome to filter out Chrome:

var ua = navigator.userAgent.toLowerCase(); 
if (ua.indexOf('safari') != -1) { 
  if (ua.indexOf('chrome') > -1) {
    alert("1") // Chrome
  } else {
    alert("2") // Safari
  }
}
197
votes

Note: always try to detect the specific behavior you're trying to fix, instead of targeting it with isSafari?

As a last resort, detect Safari with this regex:

var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

It uses negative look-arounds and it excludes Chrome, Edge, and all Android browsers that include the Safari name in their user agent.

107
votes

As other people have already noted, feature detection is preferred over checking for a specific browser. One reason is that the user agent string can be altered. Another reason is that the string may change and break your code in newer versions.

If you still want to do it and test for any Safari version, I'd suggest using this

var isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 &&
               navigator.userAgent &&
               navigator.userAgent.indexOf('CriOS') == -1 &&
               navigator.userAgent.indexOf('FxiOS') == -1;

This will work with any version of Safari across all devices: Mac, iPhone, iPod, iPad.

Edit

To test in your current browser: https://jsfiddle.net/j5hgcbm2/

Edit 2

Updated according to Chrome docs to detect Chrome on iOS correctly

It's worth noting that all Browsers on iOS are just wrappers for Safari and use the same engine. See bfred.it's comment on his own answer in this thread.

Edit 3

Updated according to Firefox docs to detect Firefox on iOS correctly

90
votes

Just use:

var isSafari = window.safari !== undefined;
if (isSafari) console.log("Safari, yeah!");
24
votes

This code is used to detect only safari browser

if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) 
{
   alert("Browser is Safari");          
}
18
votes

Because userAgent for chrome and safari are nearly the same it can be easier to look at the vendor of the browser

Safari

navigator.vendor ==  "Apple Computer, Inc."

Chrome

navigator.vendor ==  "Google Inc."

FireFox (why is it empty?)

navigator.vendor ==  ""

IE (why is it undefined?)

navigator.vendor ==  undefined
10
votes

I don't know why the OP wanted to detect Safari, but in the rare case you need browser sniffing nowadays it's problably more important to detect the render engine than the name of the browser. For example on iOS all browsers use the Safari/Webkit engine, so it's pointless to get "chrome" or "firefox" as browser name if the underlying renderer is in fact Safari/Webkit. I haven't tested this code with old browsers but it works with everything fairly recent on Android, iOS, OS X, Windows and Linux.

<script>
    let browserName = "";

    if(navigator.vendor.match(/google/i)) {
        browserName = 'chrome/blink';
    }
    else if(navigator.vendor.match(/apple/i)) {
        browserName = 'safari/webkit';
    }
    else if(navigator.userAgent.match(/firefox\//i)) {
        browserName = 'firefox/gecko';
    }
    else if(navigator.userAgent.match(/edge\//i)) {
        browserName = 'edge/edgehtml';
    }
    else if(navigator.userAgent.match(/trident\//i)) {
        browserName = 'ie/trident';
    }
    else
    {
        browserName = navigator.userAgent + "\n" + navigator.vendor;
    }
    alert(browserName);
</script>

To clarify:

  • All browsers under iOS will be reported as "safari/webkit"
  • All browsers under Android but Firefox will be reported as "chrome/blink"
  • Chrome, Opera, Blisk, Vivaldi etc. will all be reported as "chrome/blink" under Windows, OS X or Linux
10
votes

In my case I needed to target Safari on both iOS and macOS. This worked for me:

if (/apple/i.test(navigator.vendor)) {
  // It's Safari
}
7
votes

Only Safari whitout Chrome:

After trying others codes I didn't find any that works with new and old versions of Safari.

Finally, I did this code that's working very well for me:

var ua = navigator.userAgent.toLowerCase(); 
var isSafari = false;
try {
  isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
}
catch(err) {}
isSafari = (isSafari || ((ua.indexOf('safari') != -1)&& (!(ua.indexOf('chrome')!= -1) && (ua.indexOf('version/')!= -1))));

//test
if (isSafari)
{
  //Code for Safari Browser (Desktop and Mobile)
  document.getElementById('idbody').innerHTML = "This is Safari!";
}
else
{
  document.getElementById('idbody').innerHTML = "Not is Safari!";
}
<body id="idbody">
</body>
6
votes

I observed that only one word distinguishes Safari - "Version". So this regex will work perfect:

/.*Version.*Safari.*/.test(navigator.userAgent)
5
votes

I use this

function getBrowserName() {
    var name = "Unknown";
    if(navigator.userAgent.indexOf("MSIE")!=-1){
        name = "MSIE";
    }
    else if(navigator.userAgent.indexOf("Firefox")!=-1){
        name = "Firefox";
    }
    else if(navigator.userAgent.indexOf("Opera")!=-1){
        name = "Opera";
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1){
        name = "Chrome";
    }
    else if(navigator.userAgent.indexOf("Safari")!=-1){
        name = "Safari";
    }
    return name;   
}

if( getBrowserName() == "Safari" ){
    alert("You are using Safari");
}else{
    alert("You are surfing on " + getBrowserName(name));
}
5
votes

Read many answers and posts and determined the most accurate solution. Tested in Safari, Chrome, Firefox (desktop and iOS versions). First we need to detect Apple vendor and then exclude Chrome and Firefox (for iOS).

let isSafari = navigator.vendor.match(/apple/i) &&
             !navigator.userAgent.match(/crios/i) &&
             !navigator.userAgent.match(/fxios/i);

if (isSafari) {
  //
} else {
  //
}
4
votes

Simplest answer:

function isSafari() {
 if (navigator.vendor.match(/[Aa]+pple/g).length > 0 ) 
   return true; 
 return false;
}
3
votes

For the records, the safest way I've found is to implement the Safari part of the browser-detection code from this answer:

const isSafari = window['safari'] && safari.pushNotification &&
    safari.pushNotification.toString() === '[object SafariRemoteNotification]';

Of course, the best way of dealing with browser-specific issues is always to do feature-detection, if at all possible. Using a piece of code like the above one is, though, still better than agent string detection.

2
votes

Modified regex for answer above

var isSafari = /^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent);
  • crios - Chrome
  • fxios - Firefox
2
votes

I know this question is old, but I thought of posting the answer anyway as it may help someone. The above solutions were failing in some edge cases, so we had to implement it in a way that handles iOS, Desktop, and other platforms separately.

function isSafari() {
    var ua = window.navigator.userAgent;
    var iOS = !!ua.match(/iP(ad|od|hone)/i);
    var hasSafariInUa = !!ua.match(/Safari/i);
    var noOtherBrowsersInUa = !ua.match(/Chrome|CriOS|OPiOS|mercury|FxiOS|Firefox/i)
    var result = false;
    if(iOS) { //detecting Safari in IOS mobile browsers
        var webkit = !!ua.match(/WebKit/i);
        result = webkit && hasSafariInUa && noOtherBrowsersInUa
    } else if(window.safari !== undefined){ //detecting Safari in Desktop Browsers
        result = true;
    } else { // detecting Safari in other platforms
        result = hasSafariInUa && noOtherBrowsersInUa
    }
    return result;
}
1
votes

This unique "issue" is 100% sign that browser is Safari (believe it or not).

if (Object.getOwnPropertyDescriptor(Document.prototype, 'cookie').descriptor === false) {
   console.log('Hello Safari!');
}

This means that cookie object descriptor is set to false on Safari while on the all other is true, which is actually giving me a headache on the other project. Happy coding!

0
votes

Maybe this works :

Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor')

EDIT: NO LONGER WORKING

0
votes

I tested the code posted by #Christopher Martin, and it reported my browser as Chrome, because it tests for that before testing for Edge, which would otherwise answer true to the test that is intended to identify Chrome. I amended his answer to correct that deficiency and two others, namely:

  1. The abbreviated user agent substring for Edge
  2. The very old string for MSIE

Converting the code into a function yields the following function and test script that reports via the debug console.

    <script type="text/javascript">
    function BasicBrowserSniffer ( )
    {
        if ( navigator.userAgent.match ( /edge\//i ) ) {
            return 'edge/edgehtml';
        }
        if ( navigator.userAgent.match ( /edg\//i ) ) {
            return 'edge/edgehtml';
        }
        else if ( navigator.vendor.match ( /google/i ) ) {
            return 'chrome/blink';
        }
        else if ( navigator.vendor.match ( /apple/i ) ) {
            return 'safari/webkit';
        }
        else if ( navigator.userAgent.match ( /firefox\//i ) ) {
            return 'firefox/gecko';
        }
        else if ( navigator.userAgent.match ( /trident\//i ) ) {
            return 'ie/trident';
        }
        else if ( navigator.userAgent.match ( /msie\//i ) ) {
            return 'ie/trident';
        }
        else
        {
            return navigator.userAgent + "\n" + navigator.vendor;
        }
    };  // BasicBrowserSniffer function

    console.info ( 'Entering function anonymous DocumentReady function' );
    console.info ( 'User Agent String   = ' + navigator.userAgent.toLowerCase ( ));
    console.info ( 'User Agent Vendor   = ' + var uav = navigator.vendor.toLowerCase ( );
    console.info ( 'BasicBrowserSniffer = ' + BasicBrowserSniffer ( ) );
    console.info ( 'Leaving function anonymous DocumentReady function' );
</script>
-1
votes

I create a function that return boolean type:

export const isSafari = () => navigator.userAgent.toLowerCase().indexOf('safari') !== -1
-4
votes

User agent sniffing is really tricky and unreliable. We were trying to detect Safari on iOS with something like @qingu's answer above, it did work pretty well for Safari, Chrome and Firefox. But it falsely detected Opera and Edge as Safari.

So we went with feature detection, as it looks like as of today, serviceWorker is only supported in Safari and not in any other browser on iOS. As stated in https://jakearchibald.github.io/isserviceworkerready/

Support does not include iOS versions of third-party browsers on that platform (see Safari support).

So we did something like

if ('serviceWorker' in navigator) {
    return 'Safari';
}
else {
    return 'Other Browser';
}

Note: Not tested on Safari on MacOS.