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
}

How to detect Chrome with JavaScript

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

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>

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));

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?

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.
2 comments

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*