Explain Codes LogoExplain Codes Logo

How to detect Safari, Chrome, IE, Firefox and Opera browsers?

javascript
browser-detection
feature-detection
progressive-enhancement
Alex KataevbyAlex Kataev·Nov 8, 2024
TLDR

You can quickly detect a browser using navigator.userAgent and regex JavaScript:

const ua = navigator.userAgent; const isSafari = /safari/i.test(ua) && !/chrome/i.test(ua); // Because Chrome sometimes wants to be Safari const isChrome = /chrome/i.test(ua) && !/edge/i.test(ua); // Edge is the new Internet Explorer const isIE = /msie|trident/i.test(ua); // IE keeps a Trident up her sleeve const isFirefox = /firefox/i.test(ua); // Firefox is too honest const isOpera = /opera|opr\//i.test(ua); // Opera has an identity crisis console.log(`Safari: ${isSafari}, Chrome: ${isChrome}, IE: ${isIE}, Firefox: ${isFirefox}, Opera: ${isOpera}`);

Quick tip: This solution is best for UI adjustments. For critical features, consider using feature detection to avoid spoofing.

Expand your regex knowledge

Updated for the times

With frequent browser updates changing userAgent strings and APIs, you need to keep your detection scripts up to date and regularly tested with actual browser versions.

But avoid pitfalls

You might get false positives where detection results aren't as expected due to overlaps in userAgent strings or unexpected browser behavior changes. To avoid this, extensive testing and updates are necessary.

Speed it up

Browser detection might cause performance issues. Consider caching detection results during a user's session to reduce the impact and speed up calculations.

Feature detection: An extra step forward

What's this feature detection?

Feature detection helps you identify browser capabilities more reliably than userAgent string. Libraries like Modernizr help test for specific features before executing code, ensuring a better user experience.

Libraries for backup

If necessary, use reliable libraries like Bowser, Platform.js or is.js for more robust detection. They keep your detection code clean and frequently updated.

The case of Internet Explorer

For Internet Explorer, you might need conditional compilation to check versions or features specific to it. To detect IE11, use the snippet !!navigator.userAgent.match(/Trident.*rv\:11\./).

Diving into advanced detection

Conditional execution: An old friend

Conditional execution for Internet Explorer lets you execute IE-specific code snippets. But this approach is a last resort meant only for legacy projects which still require IE support.

Balance with progressive enhancement

Use libraries like Modernizr for feature detection as the basis for progressive enhancement, ensuring a more seamless experience across all browsers.

Validate features

Always validate feature support by using resources like canIuse.com. They keep you updated on the most current data, reducing the need for browser detection.