Detect Safari browser
Asked Answered
B

24

259

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;

}
Berriman answered 30/10, 2011 at 10:42 Comment(5)
Some of JS code related to file submitting works deferentially for Safari, for Chrome works fine.Berriman
You should almost certainly be testing for whatever differences in the APIs there are. There are other WebKit based browsers beyond Safari and Chrome.Bud
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.Arbour
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)Mcculley
possible duplicate of How to detect chrome and safari browser (webkit)Conciliator
H
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
  }
}
Huffish answered 30/10, 2011 at 10:48 Comment(8)
Doesn't work. Currently outputting chrome UA string on iPhone and it doesn't even have the word "chrome" in it.Phocaea
IE 11 UA string in Windows 10 also contains Safari and ChromeNeale
Blackberry also includes "Safari."Harod
@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.Eldreeda
This does not work on Android browsers, which includes "safari" but not "chrome": developers.whatismybrowser.com/useragents/explore/software_name/…Marcellusmarcelo
Downvoted, as unreliable solution - better answers below.Lukin
as mentioned, this method didn't age well, this would detect Microsoft Edge as Chrome.Garzon
UA string in mac osx chrome contains 'chrome' and 'safari'Slighting
A
257

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.

Adjudication answered 7/5, 2014 at 16:1 Comment(11)
This doesn't work. I'm still getting true if I'm using Chrome Browser on an iPhone.Bacterin
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.Adjudication
Dude this worked for me!!! Thanks a ton.. navigator.userAgent was returning values like "5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36" for both Chrome in Windows and Safari in mac.Rogozen
Not working. This says true for stock android browser.Irreparable
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.Adjudication
true. We should stick with feature detection for this kind of stuff. Modernizr covers most of the edge cases (for example Image Orientation which only works for mobile Safari). I ended up using Modernizr rather than using the User Agent.Irreparable
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.Adjudication
This was exactly what I needed. I like to use SVG images for logos where possible, but Safari just kept butchering their proportions, so I needed something to detect just Safari so I could run a small script to swap out all the SVG's for PNG's. Thanks for this!Spoken
@Tessa are you sure that's necessary? You probably just needed preserveAspectRatioAdjudication
@bfred.it I didn't know about that! I'm relatively new to using SVG's in my work so I'll definitely try it out instead!Spoken
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.Match
W
132

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

Whitted answered 30/7, 2015 at 19:20 Comment(10)
Thanks for the comment - Updated to detect Chrome on iOS correctlyWhitted
@Whitted - I don't understand this javascript, how would I do something like - if(safaribrowser) { do this } else { do that } using the same code what value is 'var isSafari' thanksEatmon
@GAV: isSafari will be true in a Safari browser, false otherwise. You can simply use the above snippet and then use yours almost as you posted it. if (isSafari) { do_this(); } else { do_that(); }.Whitted
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.Natter
Chrome on iOS is kinda Safari as it uses a Safari Webkit engine, it's not really Chrome.Sori
Works correctly with Safari/Chrome, but thinks Firefox isSafari on mobile on my iPhone.Robbins
@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/…)Springlet
Thanks @Andras for reporting the issue with Firefox on iOS and Petri Pellinen for providing a fix.Whitted
This solution works for me. but it is detecting Safari = true on Opera Iphone device. added navigator.userAgent.indexOf('OPT') == -1 for it to detect Opera isSafari = false. @WhittedCharbonneau
Thanks for reporting @ManuelAzar. It seems like according to developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… that for the desktop version Opera includes OPR/<version>. In this case we're looking for the iOS specific versions though, which according to whatmyuseragent.com/browser/o1/opera-mini-ios/16 looks like OPiOS/<version>. If somebody could confirm that's correct I'll update the answer. Thanks!Whitted
H
128

Just use:

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

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

Hengelo answered 12/2, 2017 at 15:34 Comment(10)
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.Firing
this is perfect way to determine desktop safari as this is doesnt work on mobileOdious
What versions of Safari does this work for? Doesn't seem to work for v5.1.7Procrustes
If you only care about browsers, and not mobile vs desktop, this works perfectly.Hypoderma
This didn't work inside iPhone 11 Pro Max Simulator 13.5Clepsydra
I should note that this only works for Safari on macOS which, in my case, is perfect. Thanks!Smoky
it doesn't work for me. i'm using safari Version 14.0 (15610.1.28.1.9, 15610) on macShakta
window.safari is undefined inside iframes on desktop now.Selfhelp
Alternatively and for TypeScript, use "safari" in windowGallous
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 iOSParaphrast
H
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
  }
}
Huffish answered 30/10, 2011 at 10:48 Comment(8)
Doesn't work. Currently outputting chrome UA string on iPhone and it doesn't even have the word "chrome" in it.Phocaea
IE 11 UA string in Windows 10 also contains Safari and ChromeNeale
Blackberry also includes "Safari."Harod
@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.Eldreeda
This does not work on Android browsers, which includes "safari" but not "chrome": developers.whatismybrowser.com/useragents/explore/software_name/…Marcellusmarcelo
Downvoted, as unreliable solution - better answers below.Lukin
as mentioned, this method didn't age well, this would detect Microsoft Edge as Chrome.Garzon
UA string in mac osx chrome contains 'chrome' and 'safari'Slighting
H
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");          
}
Hibbert answered 22/4, 2014 at 5:34 Comment(4)
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.24Quelpart
tossing platform detection can perhaps filter out specific compatibility cases.Needleful
I just checked a half dozen third party iOS browsers, they all spoof the very exact Safari User-Agent.Neoclassic
So this will only detect Chrome. And yet, I just found out Chrome 44 no longer has Chrome in the UA, but 'CriOS' instead :(Neoclassic
O
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
}
Offload answered 28/11, 2020 at 9:13 Comment(0)
A
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
Alter answered 1/12, 2016 at 22:6 Comment(8)
I was looking for something to disable warning messages in safari at work on various computers (mac desktops, ipads, etc), and this worked perfectly.Glim
But vendor for Chrome on iOS will also be "Apple Computer, Inc.". Sorry...Alford
@PiotrKowalski - which solution did you go with?Alter
@Alter See my answer at the bottom of this page with "version" word.Alford
@Alter I can see that my solution (see one of the answers below in this thread) still works even for newest Safari. codepen.io/SOOLTECH/pen/gOrvgXoAlford
This failed for the edge versions based on chrome!Limicolous
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.Fennessy
"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.Tamathatamaulipas
P
16

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.

Note that if people are using WKWebView for app development tailored to an Apple device, it may claim it is Safari, which is technically true, given that it uses Safari's web features in the background. Other solutions may be necessary, such as injecting additional code.

Predesignate answered 4/1, 2022 at 21:42 Comment(4)
How would you practically detect if the event exists?Boden
@Boden You can check typeof window.GestureEvent === 'function'Bracci
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.Kozlowski
It does not work for mobile devices. When you open Chrome on IO, it shows that it's Safary.Macrobiotic
P
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
Pawl answered 21/9, 2018 at 14:25 Comment(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 edgThomasinethomason
This should be the new accepted answer, thank you Christopher.Enlil
2023 - Answer worked for me. Tested Desktop only. Haven't tested mobile.Protractile
R
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
}
Rothman answered 6/10, 2020 at 9:55 Comment(6)
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/15E148Cognac
Any reason to use regex for this instead of just doing navigator.vendor === "Apple Computer, Inc."?Coppice
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 meRothman
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...Propylaeum
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.Rothman
Tested on a: - macOS (Ventura) Chrome 108: false - macOS Safari: true - iOS Safari: true - iOS Chrome: couldn't testPyrrha
M
7

Only Safari whitout Chrome:

After trying other's code 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 = "This is not Safari!";
}
<body id="idbody"></body>
Mary answered 2/3, 2017 at 18:2 Comment(0)
A
6

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

/.*Version.*Safari.*/.test(navigator.userAgent)
Alford answered 8/5, 2018 at 12:36 Comment(0)
L
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));
}
Lasko answered 20/6, 2016 at 4:26 Comment(0)
U
5

Simplest answer:

function isSafari() {
 if (navigator.vendor.match(/[Aa]+pple/g).length > 0 ) 
   return true; 
 return false;
}
Unblown answered 4/9, 2019 at 7:37 Comment(5)
It works, although could be done simpler without regexp: navigator.vendor.toLowerCase().indexOf('apple') > -1Lowrey
Even simpler... if (navigator.vendor.match(/apple/i)) { ... }.Teens
This doesn't work for ios 13.3.1 on firefox as it shows Apple Computer, incSentinel
@nuttynibbles: This is probably what you want because every browser on iOS is a Safari in disguise.Postdate
You could even do navigator.vendor.indexOf("pple") if you felt like it, but there really isn't a speed difference.Predesignate
B
4

Modified regex for answer above

var isSafari = /^((?!chrome|android|crios|fxios).)*safari/i.test(navigator.userAgent);
  • crios - Chrome
  • fxios - Firefox
Brunson answered 7/11, 2016 at 10:36 Comment(0)
H
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;
}
Halbert answered 8/5, 2018 at 1:22 Comment(0)
G
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.

Graphophone answered 13/8, 2019 at 7:50 Comment(1)
This doesn't work with safari Version/13.1 Mobile/15E148 Safari/604.1 on iPhone OS 13_4_1.Lagomorph
P
2

2023 edition

if(navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome')){
    // it's safari
    console.log('safari detected');
}
Previdi answered 11/7, 2023 at 3:11 Comment(0)
B
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!

Bornholm answered 19/5, 2018 at 22:39 Comment(1)
Seems no longer true. Also crashes on Firefox "Object.getOwnPropertyDescriptor(...) is undefined"Soil
P
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>
Portemonnaie answered 15/5, 2021 at 21:39 Comment(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.Pawl
F
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
}
Fults answered 2/8, 2021 at 12:47 Comment(0)
R
1

2024 Version

  var ua = window.navigator.userAgent;
  var iOS = ua.match(/Macintosh/i) || ua.match(/iPad/i) || ua.match(/iPhone/i);
  var webkit = ua.match(/WebKit/i);
  var iOSSafari = iOS && webkit && !ua.match(/CriOS/i) && !ua.match(/EdgiOS/i) && !ua.match(/Chrome/i) && !ua.match(/Edg/i);

    if (iOSSafari) {
        //do stuff here
    }
Roslyn answered 15/1 at 19:44 Comment(0)
M
-1

I create a function that return boolean type:

export const isSafari = () => navigator.userAgent.toLowerCase().indexOf('safari') !== -1
Many answered 28/4, 2020 at 15:13 Comment(0)
P
-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.

Patagonia answered 11/6, 2020 at 12:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.