252

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;

}
5
  • 1
    Some of JS code related to file submitting works deferentially for Safari, for Chrome works fine.
    – Tomas
    Oct 30, 2011 at 10:49
  • 1
    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
    Oct 30, 2011 at 12:48
  • 20
    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. Jun 1, 2012 at 6:21
  • 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
    May 24, 2013 at 12:56
  • 1
    possible duplicate of How to detect chrome and safari browser (webkit)
    – anik4e
    Nov 24, 2014 at 9:58

23 Answers 23

248

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.

11
  • 3
    This doesn't work. I'm still getting true if I'm using Chrome Browser on an iPhone.
    – ayjay
    Feb 23, 2015 at 23:09
  • 54
    That's because all browsers on iOS are just wrappers for Safari (with the exception of Opera Mini in Mini mode), including Chrome. This doesn't necessarily mean that they'll all match this test since the userAgent string is up to the wrapper. You might want to detect Chrome on iOS separately.
    – fregante
    Feb 24, 2015 at 7:25
  • 2
    Fixed now. You're definitely right, the problem with a lot of browsers is that they include other names to try not to be left out. Like Edge includes both Chrome and Safari in its UA. User agent checks are bad for this reason: browsers change and the checks need to be updated. Unfortunately there's no perfect way to detect a browser, it's always a guess.
    – fregante
    Oct 29, 2015 at 12:32
  • 2
    Definitely a good idea to use feature detection, but some behaviors are just hard or nearly impossible to test, for example whether videos on mobile go automatically fullscreen, something that only happens on the iPhone and iPod. To test it, you need to load a video and have the user play it.
    – fregante
    Nov 11, 2015 at 6:27
  • 2
    For what it's worth, I've found that safari's background-color property silently fails with partial transparency colour values. That is, it "does" "render" the color, it just renders it as transparent. Anything that overrides that will also override the intended color in other browsers. Point being, feature detection is just sometimes not the way. Mar 30, 2021 at 17:25
130

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

8
  • Thanks for the comment - Updated to detect Chrome on iOS correctly
    – qingu
    Nov 7, 2015 at 19:46
  • 8
    Unfortunately there's more more reasons to try to figure out the browser than just feature detection. A browser can support a feature, but be buggy (ex: canvas bug in IE10, but the same feature works in IE9). Also Firefox behaves differently than webkit based browsers, such as how it responds to mouse movement. Apple's Safari has reflow bugs that don't exist in Chrome. Some browsers are also performant when doing certain computationally intensive tasks than others.
    – DemiImp
    Oct 12, 2016 at 4:15
  • 1
    Works correctly with Safari/Chrome, but thinks Firefox isSafari on mobile on my iPhone.
    – M3RS
    Feb 8, 2018 at 8:46
  • 3
    @Andras For Firefox you can add && !navigator.userAgent.match('FxiOS') similar to the Chrome check - ref (developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/…) Jul 6, 2018 at 7:38
  • 1
    Thanks @Andras for reporting the issue with Firefox on iOS and Petri Pellinen for providing a fix.
    – qingu
    Jul 13, 2018 at 0:24
126

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
  }
}
8
  • 8
    Doesn't work. Currently outputting chrome UA string on iPhone and it doesn't even have the word "chrome" in it. Jul 1, 2014 at 22:59
  • 8
    IE 11 UA string in Windows 10 also contains Safari and Chrome
    – cuixiping
    Apr 17, 2015 at 14:31
  • 26
    @Flimm There are many legitimate use cases for browser detection. Do not presume to know the asker or answerer's intention. While it's great to include a helpful tip you may believe to be relevant, it's by no means a requirement. Apr 10, 2018 at 13:56
  • 3
    Downvoted, as unreliable solution - better answers below.
    – Oli C
    Jul 22, 2019 at 12:38
  • 2
    as mentioned, this method didn't age well, this would detect Microsoft Edge as Chrome.
    – damianmr
    Oct 12, 2020 at 22:12
126

Just use:

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

Note this might not be reliable for mobile versions of Safari.

10
  • 19
    Not sure why this isnt higher up - is this is perfect, short, and simple. I needed to rule out desktop safari for the lack of getUserMedia. Jun 6, 2017 at 19:27
  • 8
    this is perfect way to determine desktop safari as this is doesnt work on mobile Mar 16, 2018 at 10:27
  • 10
    This didn't work inside iPhone 11 Pro Max Simulator 13.5 Jul 8, 2020 at 7:48
  • 8
    I should note that this only works for Safari on macOS which, in my case, is perfect. Thanks!
    – Twyx
    Feb 12, 2021 at 19:57
  • 4
    I want to warn everyone, that this is not a reliable way of detection. We got burned by this when we realized, that this doesn't work in safari on iPad OS and iOS
    – Phil Rukin
    Sep 30, 2022 at 17:57
27

This code is used to detect only safari browser

if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) 
{
   alert("Browser is Safari");          
}
4
  • 7
    this code only detects wether a webkit browser is not chrome. Many other browsers have the bad idea of including "safari" in their user agent string. For example, Opera: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36 OPR/24.0.1558.51 (Edition Next), or Stock Android browser: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.34 Safari/534.24
    – rupps
    Jan 17, 2015 at 0:14
  • tossing platform detection can perhaps filter out specific compatibility cases.
    – ljgww
    May 11, 2015 at 8:49
  • I just checked a half dozen third party iOS browsers, they all spoof the very exact Safari User-Agent. Nov 7, 2015 at 8:49
  • So this will only detect Chrome. And yet, I just found out Chrome 44 no longer has Chrome in the UA, but 'CriOS' instead :( Nov 7, 2015 at 9:02
23

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

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

if (isSafari) {
  // Safari browser is used
} else {
  // Other browser is used
}
22

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
8
  • 1
    I was looking for something to disable warning messages in safari at work on various computers (mac desktops, ipads, etc), and this worked perfectly.
    – dylnmc
    Jun 23, 2017 at 17:48
  • 1
    But vendor for Chrome on iOS will also be "Apple Computer, Inc.". Sorry... May 8, 2018 at 12:33
  • 1
    This failed for the edge versions based on chrome!
    – Qiulang
    Oct 16, 2020 at 7:07
  • 1
    Most brilliant and easiest solution. Usually you want to catch Safari, since it is the newer IE - to fix javascript things it does not support - like it should. Even Chrome in iOS is based on Safari-engine and got the same bad support as Safari. And this in a simple way, detects Safari in Mac OS, Safari and Chrome in iOS. Splendid.
    – JoakimB
    Dec 17, 2021 at 11:58
  • 1
    "But vendor for Chrome on iOS will also be "Apple Computer, Inc.". Sorry.." That's because Chrome is Safari on iOS, so that's exactly what you want. The point is not to figure out the branding of the browser, it's to figure out what engine you're dealing with, so you can work around engine-specific bugs.
    – Mud
    Oct 8, 2022 at 20:04
17

Detect gesture change support, like this:

const isSafari = !!window.GestureEvent
document.write(isSafari ? "You are using Safari." : "You are not using Safari.")

Nice and simple; works for iOS and Android! If you need ES5 support, replace const with var.

4
  • 1
    How would you practically detect if the event exists?
    – Hicka
    Mar 11, 2022 at 18:38
  • 3
    @Hicka You can check typeof window.GestureEvent === 'function'
    – Jankapunkt
    Mar 15, 2022 at 13:57
  • 2
    Or: if ('GestureEvent' in window) {window.alert('This is WebKit');}. Note that this check detects WebKit rather than Safari - but if you are looking for a match with Safari on Desktop and all browsers on iOS (on iOS, Chrome Mobile, Safari Mobile etc. are all just Safari Mobile with a different skin) detecting WebKit (rather than "Safari") is probably what you want.
    – Rounin
    May 9, 2022 at 9:53
  • That was exactly what i was looking for, thank you.
    – mtness
    Jun 19 at 7:35
13

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
3
  • Old versions of IE have the string MSIE not Trident. Sometimes edge is missing the final e in the word edge. You have to search for edg
    – PHP Guru
    Oct 31, 2020 at 16:10
  • This should be the new accepted answer, thank you Christopher.
    – Myndex
    Nov 1, 2020 at 23:33
  • 2023 - Answer worked for me. Tested Desktop only. Haven't tested mobile. Aug 1 at 5:46
12

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
}
6
  • 1
    Thanks! This also can detect WKWebView which does not contain Safari string: Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
    – mikep
    Feb 22, 2021 at 2:51
  • Any reason to use regex for this instead of just doing navigator.vendor === "Apple Computer, Inc."?
    – Newbyte
    Mar 4, 2021 at 21:23
  • Honestly I don't know what navigator.vendor might possibly contain, but in my specific case I needed to target any Apple browser in general, so the regex worked for me
    – Simone
    Mar 5, 2021 at 9:37
  • 2
    Does NOT work! It only detects if it is iOS or macOS. If I use Firefox, Chrome or Opera it still says i use Safari...
    – MrMaavin
    Sep 23, 2021 at 9:53
  • 2
    How so? On Chrome, navigator.vendor is Google Inc. and therefore the test returns false (it's not Safari). Firefox returns an empty string for me, which also evaluates to false. So this seems to work well in general for detecting Safari.
    – Simone
    Jul 20, 2022 at 18:30
7

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>

0
6

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

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

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

Simplest answer:

function isSafari() {
 if (navigator.vendor.match(/[Aa]+pple/g).length > 0 ) 
   return true; 
 return false;
}
5
  • 3
    It works, although could be done simpler without regexp: navigator.vendor.toLowerCase().indexOf('apple') > -1
    – fviktor
    Oct 8, 2019 at 4:39
  • 6
    Even simpler... if (navigator.vendor.match(/apple/i)) { ... }.
    – Brad
    Dec 1, 2019 at 18:53
  • This doesn't work for ios 13.3.1 on firefox as it shows Apple Computer, inc Mar 19, 2020 at 8:46
  • 3
    @nuttynibbles: This is probably what you want because every browser on iOS is a Safari in disguise.
    – wortwart
    Jul 14, 2020 at 11:53
  • You could even do navigator.vendor.indexOf("pple") if you felt like it, but there really isn't a speed difference.
    – Infigon
    Aug 1, 2022 at 16:38
4

Modified regex for answer above

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

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

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.

1
  • 1
    This doesn't work with safari Version/13.1 Mobile/15E148 Safari/604.1 on iPhone OS 13_4_1.
    – mindo
    Apr 24, 2020 at 10:32
1

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!

1
  • Seems no longer true. Also crashes on Firefox "Object.getOwnPropertyDescriptor(...) is undefined"
    – Offirmo
    Mar 20, 2019 at 5:05
1

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
  • This code is not an improvement. As I stated in my post it is not about detecting browser names but browser engines. Your code detects the new Edge which uses blink engine as edgehtml which is the completely different render engine of the old Edge. The Blink version uses edg instead of edge in the UA to make the difference. Aug 2 at 7:43
1

Based on @SudarP answer.

At Q3 2021 this solution will fail in either Firefox (Uncaught TypeError: navigator.vendor.match(...) is null) and Chrome (Uncaught TypeError: Cannot read properties of null (reading 'length'));

So here is a fixed and shorter solution:

function isSafari() {
  return (navigator.vendor.match(/apple/i) || "").length > 0
}
1

2023 edition

if(navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome')){
    // it's safari
    console.log('safari detected');
}
-1

I create a function that return boolean type:

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

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.