How to Reliably Detect Browser Type
When developing browser-specific extensions, it's crucial to accurately identify the user's browser. Detecting browser types is essential for serving the correct addon for each browser.
Problematic Detection Methods
One common approach is checking the user agent string. However, this method is unreliable because attackers can easily spoof this value. Hence, it's necessary to employ more reliable techniques.
Browser Duck-Typing
Duck-typing is a more reliable method for browser detection. Here's a JavaScript code snippet that employs this approach:
// Opera 8.0+ var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; // Firefox 1.0+ var isFirefox = typeof InstallTrigger !== 'undefined'; // Safari 3.0+ "[object HTMLElementConstructor]" var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification)); // Internet Explorer 6-11 var isIE = /*@cc_on!@*/false || !!document.documentMode; // Edge 20+ var isEdge = !isIE && !!window.StyleMedia; // Chrome 1 - 79 var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime); // Edge (based on chromium) detection var isEdgeChromium = isChrome && (navigator.userAgent.indexOf("Edg") != -1); // Blink engine detection var isBlink = (isChrome || isOpera) && !!window.CSS;
Feature Detection vs. Browser Detection
When possible, opt for feature detection over browser detection. Feature detection involves checking whether specific functions or objects exist, providing a more reliable and browser-independent approach.
Example Usage
To utilize the browser detection code, follow these steps:
Remember to use browser detection sparingly and only when necessary, such as displaying browser-specific installation instructions. Feature detection should be your primary tool for ensuring compatibility and optimizing user experience.
The above is the detailed content of How to Reliably Detect Browser Type in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!