Sunday, September 16, 2012

Browser type: window.navigator in JavaScript

window.navigator returns a reference to the navigator object:
 The detail of properties and methods of window.navigato can be found:

One of the method navigator.userAgent
Returns the user agent string for the current browser.
    <script type="text/javascript">

Return in my local computer:
Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1  
To get Firefox/x.x or Firefox x.x, string.match is to find the match pattern
 var firefox= /Firefox[\/\s](\d+\.\d+)/;
which returns 
Use Number(RegExp.$1)
to return Firefox version 15 and convert to number.

Final code to detect Firefox and return version in JavaScript:
     <script type="text/javascript">
        var firefox= /Firefox[\/\s](\d+\.\d+)/;
       if( window.navigator.userAgent.match(firefox))  
       document.write("Firefox version "+Number(RegExp.$1));

Note RegExp.$1 returns the first match pattern in the last memory, i.e.(\d+\.\d+),
x.x in firefox
Similarly, for Internet Explorer:
var MSIE=/MSIE (\d+\.\d+);/;
For Opera
Var Opera=/Opera[\/\s](\d+\.\d+)/ ;
To detect operation system we can use the following JavaScript:
    <script type="text/javascript">   
      var ua=window.navigator.userAgent.toLowerCase();
         document.write("It is Windows") 
      else if(ua.indexOf("linxu")>-1)
          document.write("It is Linux")
       else if(ua.indexOf("mac")>-1)
              document.write("It is Mac");    

No comments:

Post a Comment