GeorgeU
GeorgeU

Reputation: 8669

How can I detect if a browser is Safari 5+ using Javascript?

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?

Upvotes: 1

Views: 5415

Answers (2)

Chris
Chris

Reputation: 3298

  1. 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.

  2. As a consequence of point 1. it is almost always best to use capabilities support detection (e.g. such as with Modernizr).

  3. 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.

Upvotes: 0

mvark
mvark

Reputation: 2105

I have found PPK's browser detection code to be very reliable. It utilizes navigator.vendor and navigator.userAgent.

Upvotes: 1

Related Questions