I need a method to detect that the browser is Safari 5 or higher - but the javascript should not rely on useragent since it can get overriden! Any ideas?
-
1Why do you need to prepare for the exceedingly rare case that the user agent gets spoofed? It stands to reason that somebody doing that to their browser can't expect sites to work correctly any more. There may be a way to do this using feature detection but the user-agent string is the most common way to detect a browser version.Pekka– Pekka2011-11-29 23:43:46 +00:00Commented Nov 29, 2011 at 23:43
-
6It is much, much better to detect a specific feature you are interested in than to test a browser version. What problem are you actually trying to solve?jfriend00– jfriend002011-11-29 23:53:17 +00:00Commented Nov 29, 2011 at 23:53
-
I have a script that does not work in pre safari 5, so trying to check on a feature. Was relyong on Websocket...but wondered if someone had written something betterGeorgeU– GeorgeU2011-12-01 17:28:24 +00:00Commented Dec 1, 2011 at 17:28
-
Similar question, with answers stackoverflow.com/questions/4227982/…Ellie K– Ellie K2011-12-13 01:23:46 +00:00Commented Dec 13, 2011 at 1:23
2 Answers
I have found PPK's browser detection code to be very reliable. It utilizes navigator.vendor and navigator.userAgent.
1 Comment
It's not possible to reliably detect the browser without accepting that the user agent can be modified by the end-user and / or the browser itself.
As a consequence of point 1. it is almost always best to use capabilities support detection (e.g. such as with Modernizr).
As there are times when you need to specifically detect a browser, such as disabling or enabling a particular capability that is misreported / not detectable, e.g. File Drag and Drop in Safari 5
As an example, the following code provides a function isFileDragAndDropSupported() which makes use of the isSafari5() function to return that File Drag and Drop is supported on Safari 5 even though window.FileReader is not defined in Safari 5.
function isSafari5() {
return !!navigator.userAgent.match(' Safari/') && !navigator.userAgent.match(' Chrom') && !!navigator.userAgent.match(' Version/5.');
};
function isFileAPIEnabled () {
return !!window.FileReader;
};
function isFileDragAndDropSupported() {
var isiOS = !!navigator.userAgent.match('iPhone OS') || !!navigator.userAgent.match('iPad');
return (Modernizr.draganddrop && !isiOS && (isFileAPIEnabled() || isSafari5()));
};
Note: Modernizr is required only for the isFileDragAndDropSupported() function. The isSafari5() function will work stand-alone.