Pages

Thursday, March 20, 2014

Wednesday, March 19, 2014

How to detect IE (Internet Explorer) by using JavaScript ?

In this blog, I will demonstrate how to detect the browser IE including latest version IE 11 by using JavaScript.

Why do we need to detect a specific browser?

As every browser is backed up by its own rendering engine to draw the HTML/CSS web page, you might find some things that do not work perfectly across all the browsers.

Ex: I have recently developed a MVC web application and my requirement was to show loading animation when the form submits.



After I deployed my website to the web server and upgraded my IE to IE 11, I realized that the loading animation is not working in IE 11 browser. It was perfectly working in the other browsers like Chrome and Firefox.

Solution

I had to do some other stuff to make it work on IE by detecting the browser. I thought I could detect the browser IE 11 just by checking a ‘navigator.appName == “Microsoft Internet Explorer”’ property in the JavaScript. But, later I found out IE11 preview has changed the value of navigator.appName. Before IE11, this value is: “Microsoft Internet Explorer”.

Now with IE11 preview, Microsoft changed this value to “Netscape”.
Not only the IE11, for other browsers like Chrome and Firefox also ‘navigator.appName’ property returning ‘Netscape’.

Try the below link in different browsers to find ‘navigator.appName’ value:


To fix the above problem, I had to write a piece of code to detect the browser IE11 by using JavaScript. After a little bit of research on the internet I found this code.

$(document).ready(function () {
if (IsRequestFromIE())
    alert(‘This is IE’);
else
    alert(‘Some other browser’);
});

function IsRequestFromIE(){
   var rv = -1;
   var result = false;
   if (navigator.appName == 'Microsoft Internet Explorer')
   {
     var ua = navigator.userAgent;
     var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
     if (re.exec(ua) != null)
     rv = parseFloat( RegExp.$1 );
   }
   else if (navigator.appName == 'Netscape')
   {
     var ua = navigator.userAgent;
     var re  = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
     if (re.exec(ua) != null)
         rv = parseFloat( RegExp.$1 );
   }
   if(rv != -1)
      result = true;
      return result;
  }

As I found the solution, I thought to blog it in my blogspot. So that it might help to someone who is struggling to resolve this issue.