Detect Safari browser

JavascriptBrowser Detection

Javascript Problem Overview


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;

}

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

Just use:

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

Solution 5 - Javascript

This code is used to detect only safari browser

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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
}

Solution 8 - Javascript

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

Solution 9 - Javascript

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
}

Solution 10 - Javascript

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>

Solution 11 - Javascript

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

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

Solution 12 - Javascript

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

Solution 13 - Javascript

Modified regex for answer above

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

Solution 14 - Javascript

Simplest answer:

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

Solution 15 - Javascript

Detect gesture change.

Gesture change is supported pretty widely only on Safari (and works on on iOS): enter image description here

Solution 16 - Javascript

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

Solution 17 - Javascript

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.

Solution 18 - Javascript

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!

Solution 19 - Javascript

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>

Solution 20 - Javascript

Maybe this works :

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

EDIT: NO LONGER WORKING

Solution 21 - Javascript

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
}

Solution 22 - Javascript

I create a function that return boolean type:

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

Solution 23 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomasView Question on Stackoverflow
Solution 1 - JavascriptfreganteView Answer on Stackoverflow
Solution 2 - JavascriptdavidView Answer on Stackoverflow
Solution 3 - JavascriptqinguView Answer on Stackoverflow
Solution 4 - JavascriptlukyerView Answer on Stackoverflow
Solution 5 - JavascriptwahidView Answer on Stackoverflow
Solution 6 - JavascripttylerlindellView Answer on Stackoverflow
Solution 7 - JavascriptMichael RafailykView Answer on Stackoverflow
Solution 8 - JavascriptChristopher MartinView Answer on Stackoverflow
Solution 9 - JavascriptSimoneView Answer on Stackoverflow
Solution 10 - JavascriptleoledmagView Answer on Stackoverflow
Solution 11 - JavascriptPiotr KowalskiView Answer on Stackoverflow
Solution 12 - JavascriptlovepongView Answer on Stackoverflow
Solution 13 - JavascriptYurii SherbakView Answer on Stackoverflow
Solution 14 - JavascriptSudarPView Answer on Stackoverflow
Solution 15 - JavascriptInfiniteGamerView Answer on Stackoverflow
Solution 16 - JavascriptH HView Answer on Stackoverflow
Solution 17 - JavascriptMarcos SandriniView Answer on Stackoverflow
Solution 18 - JavascriptmaxxxView Answer on Stackoverflow
Solution 19 - JavascriptDavid A. GrayView Answer on Stackoverflow
Solution 20 - JavascriptHarshal CarpenterView Answer on Stackoverflow
Solution 21 - Javascriptuser1201917View Answer on Stackoverflow
Solution 22 - JavascriptIdanView Answer on Stackoverflow
Solution 23 - JavascriptA.G.View Answer on Stackoverflow