Tuesday, September 02, 2008

How to detect browser using JavaScript

         As a software developers we must have to deal with javascript every now and than. There are some scripts which is browser dependent. You need to write different functions for different browsers. To achieve this you must require to detect the browser. Below code may helps you,

   1: var isIE = false;
   2: var isFF = false;
   3: var isOP = false;
   4: var isSafari = false;
   5:  
   6: function DetectBrowser()
   7: {
   8:     var val = navigator.userAgent.toLowerCase();
   9:        
  10:     if(val.indexOf("firefox") > -1)
  11:     {
  12:         isFF = true;
  13:     } 
  14:     else if(val.indexOf("opera") > -1)
  15:     {
  16:         isOP = true;
  17:     }
  18:     else if(val.indexOf("msie") > -1)
  19:     {
  20:         isIE = true;
  21:     } 
  22:     else if(val.indexOf("safari") > -1)
  23:     {
  24:         isIE = true;
  25:     } 
  26:  
  27: }

Fig - (1) Code to detect browser using javascript.


Happy Programming !!!

1 comment:

Anonymous said...

function DetectBrowser()
7: {
8: var val = navigator.userAgent.toLowerCase();
9:
10: if(val.indexOf("firefox") > -1)
11: {
12: isFF = true;
13: }
14: else if(val.indexOf("opera") > -1)
15: {
16: isOP = true;
17: }
18: else if(val.indexOf("msie") > -1)
19: {
20: isIE = true;
21: }
22: else if(val.indexOf("safari") > -1)
23: {
24: isIE = true;
25: }
26:
27: }

here in line No 24 it was written as isIE instead of isSafari....