21Aug

Javascript targeting Safari only

We often say Safari and Chrome are the same in terms of HTML and CSS behaviours but it’s not always the case. Here is a bit of javascript to target Safari only. 

Chrome has both ‘Chrome‘ and ‘Safari‘ inside userAgent string.
Safari has only ‘Safari‘.

In native javascript:


var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
var is_explorer = navigator.userAgent.indexOf('MSIE') > -1;
var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
var is_opera = navigator.userAgent.toLowerCase().indexOf("op") > -1;
if ((is_chrome)&&(is_safari)) { is_safari = false; }
if ((is_chrome)&&(is_opera)) { is_chrome = false; }

Usage:
if (is_safari) { alert('Safari'); }

Or for Safari only, use this :


if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {alert('Its Safari');}

 

Source: http://stackoverflow.com/questions/5899783/detect-safari-chrome-ie-firefox-opera-with-user-agent

Subscribe
Notify of

5 Comments
Oldest
Newest
Inline Feedbacks
View all comments
nomdedieu
6 years ago

dont work on ios 10, iphone 6 , chrome work over webkit, useragent include safari string :(
not a reliable way to do this

Gabriel Moncea
4 years ago
Reply to  nomdedieu

you can try
let is_iPad = navigator.userAgent.includes(“iPad”)
let is_iPhone = navigator.userAgent.includes(“iPhone”)

titusjin
5 years ago

thanks for the info but mobile devices not included into the concern

5 years ago

Thanks your efforts are appreciated

Alicia Hubbard
4 years ago

Got this working for detecting ios safari, while avoiding false positives on chrome or firefox:
var nav = window.navigator;
var ua = nav.userAgent;

if(ua.indexOf(‘iPhone’)!=-1 && ua.indexOf(‘Safari’)!=-1 && ua.indexOf(‘CriOS’)==-1 && ua.indexOf(‘FxiOS’)==-1)

hope this helps someone else looking to solve the same problem!