Due to the differences in CSS and JS support from various browsers, we often need to check the browser type and version before writing code for their differences in front-end development! The following checkbrowser () function mainly detects three browsers (ie, Firefox, Chrome). other browsers can add detection code if they are interested!
Some HTML code:(Execute the detection function when loading the page)
<body onload="checkBrowser()"><p id="userAgent"></p><p id="browser"></p></body>
JavaScript code:The detection principle is mainly based on the browser's user proxy header nanigator. useragent extracts the browser, type, and version information, and uses regular expressions to easily meet our needs. If you are not familiar with regular expressions, refer to this article (
Regular Expression)
Function check (REG) {var ug = navigator. useragent. tolowercase (); Return Reg. test (UG);} function checkbrowser () {var ug = navigator. useragent. tolowercase (); var useragent = document. getelementbyid ("useragent"); useragent. innerhtml = "browser user proxy header:" + ug; var browsertype = ""; var ver = ""; // check IE and version var Ie = ug. match (/MSIE \ s * \ D \. \ D/); // extract the browser type and version information. Note that the match () method returns an array instead of a string var isie = check (/MSIE/); If (isie) {browsertype = "Internet Explorer"; ver = IE. join (""). match (/[0-9]/g ). join (". "); // first convert the join () method into a string, then use the match () method to match the version information, and then use join () method to string} // detect chrome and version var chrome = ug. match (/chrome \/\ D \. \ D/Gi); var ischrome = check (/Chrome/); If (ischrome) {browsertype = "Chrome"; ver = chrome. join (""). match (/[0-9]/g ). join (". ");} // detect Firefox and VAR Firefox = ug. match (/Firefox \/\ D \. \ D/Gi); var isfirefox = check (/Firefox/); If (isfirefox) {browsertype = "Firefox"; ver = Firefox. join (""). match (/[0-9]/g ). join (". ");} var browser = document. getelementbyid ("Browser"); browser. innerhtml = "your browser is:" + browsertype + "<span style = 'padding-left: 15px; '> Version: </span>" + ver ;}
PS: the user agent information of each browser is as follows:
IE:Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; BOIE9;ZHCN);firefox:Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0;chrome:Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.597.98 Safari/534.13