[javascript] Detect Safari browser

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;

}

This question is related to javascript browser-detection

The answer is


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

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

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

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

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!


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
}

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.


Simplest answer:

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

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.


Maybe this works :

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

EDIT: NO LONGER WORKING


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


Just use:

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

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

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 {
  //
}

This code is used to detect only safari browser

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

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:

_x000D_
_x000D_
var ua = navigator.userAgent.toLowerCase(); _x000D_
var isSafari = false;_x000D_
try {_x000D_
  isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);_x000D_
}_x000D_
catch(err) {}_x000D_
isSafari = (isSafari || ((ua.indexOf('safari') != -1)&& (!(ua.indexOf('chrome')!= -1) && (ua.indexOf('version/')!= -1))));_x000D_
_x000D_
//test_x000D_
if (isSafari)_x000D_
{_x000D_
  //Code for Safari Browser (Desktop and Mobile)_x000D_
  document.getElementById('idbody').innerHTML = "This is Safari!";_x000D_
}_x000D_
else_x000D_
{_x000D_
  document.getElementById('idbody').innerHTML = "Not is Safari!";_x000D_
}
_x000D_
<body id="idbody">_x000D_
</body>
_x000D_
_x000D_
_x000D_


I create a function that return boolean type:

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

Modified regex for answer above

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

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.


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