JS gets examples of browser and operating system versions

  • 2020-03-30 02:58:25
  • OfStack

So, we can write the following code:

<script type="text/javascript">
 var Sys = {};
 var ua = navigator.userAgent.toLowerCase();
 var s;
  (s = ua.match(/msie ([d.]+)/)) ? Sys.ie = s[1] :
  (s = ua.match(/firefox/([d.]+)/)) ? Sys.firefox = s[1] :
  (s = ua.match(/chrome/([d.]+)/)) ? Sys.chrome = s[1] :
  (s = ua.match(/opera.([d.]+)/)) ? Sys.opera = s[1] :
  (s = ua.match(/version/([d.]+).*safari/)) ? Sys.safari = s[1] : 0;
 //Here's the test
 if (Sys.ie) document.write('IE: ' + Sys.ie); 
 if (Sys.firefox) document.write('Firefox: ' + Sys.firefox);
 if (Sys.chrome) document.write('Chrome: ' + Sys.chrome);
 if (Sys.opera) document.write('Opera: ' + Sys.opera);
 if (Sys.safari) document.write('Safari: ' + Sys.safari);
</script>

The ternary operator is used to simplify the code. The judgment condition is an assignment statement, which not only completes the regular expression match and the result copy, but also serves as the conditional judgment directly. The subsequent version information is simply extracted from the previous match, which is very efficient code.

In the future, it will be very elegant to judge a browser only in the form of if(sys.ie) or if(sys.firefox), and the browser version only in the form of if(sys.ie == '8.0') or if(sys.firefox == '3.0').

Get operating system version:

<script type="text/javascript">
//Used to get the system version (note: this method is not valid for Firefox or Chrome)
var ua = window.navigator.userAgent;
var osVersion = ua.split(";")[2];
var osV = osVersion.substr(osVersion.length-3,3); 
switch(osV)
{
 case "5.0":
  document.write("Windows2000");
  break;
 case "5.1":
  document.write("WindowsXP");
  break;
 case "5.2":
  document.write("Windows2003");
  break;
 case "6":
  document.write("Windows Vista");
  break;
 case "6.1":
  document.write("Windows 7");
  break;
 default:
 document.write("Others");
}
</script>


Related articles: