window.navigator returns a reference to the navigator object:
The detail of properties and methods of window.navigato can be found:
https://developer.mozilla.org/en-US/docs/DOM/window.navigator
One of the method
navigator.userAgent
- Returns the user agent string for the current browser.
<script type="text/javascript">
document.write(window.navigator.userAgent);
</script>
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+)/;
window.navigator.userAgent.match(firefox);
which returns
Firefox/15.0,15.0
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));
</script>
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();
if(ua.indexOf("win")>-1)
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");
</script>
No comments:
Post a Comment