How to detect Firefox, Chrome and Internet Explorer with JavaScript

First of all keep in mind that User Agents can be spoofed, so they could be lying to you. If you need to detect a feature (animations, opacity...) use something like Modernizr instead.

How to detect Firefox with JavaScript

if( navigator.userAgent.toLowerCase().indexOf('firefox') > -1 ){
	// Do something in Firefox
}Code language: JavaScript (javascript)

How to detect Chrome with JavaScript

if( navigator.userAgent.toLowerCase().indexOf('chrome') > -1 ){
	// Do something in Chrome
}Code language: JavaScript (javascript)

How to detect Internet Explorer with JavaScript

If you need to detect IE9 and below first add the following HTML to your header:

<!doctype html>
<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html class=""> <!--<![endif]-->
<head>Code language: HTML, XML (xml)

Then use this short jQuery snippet:

(function ($) {
  "use strict";
  // Detecting IE
  var oldIE;
  if ($('html').is('.ie6, .ie7, .ie8')) {
    oldIE = true;
  }
  if (oldIE) {
    // Here's your JS for IE..
  } else {
    // ..And here's the full-fat code for everyone else
  }
}(jQuery));Code language: JavaScript (javascript)

Sadly, in IE11 they changed how we can detect it. At the time of the writing I couldn't found a reliable way. Do you know one?

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *