简体   繁体   中英

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?

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

  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 (eg 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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM