The following checkbrowser () function mainly detects three kinds of browsers (IE, Firefox, Chrome), other browsers are interested in the detection of friends can add their own detection code!
HTML Part code: (Performs a detection function on page load)
Copy Code code as follows:
<body onload= "Checkbrowser ()" >
<p id= "UserAgent" ></p>
<p id= "Browser" ></p>
</body>
JavaScript Part code:
The principle of detection is mainly based on the browser's user agent header nanigator.useragent to extract the browser and type and version information, the use of regular expressions can easily meet our needs, such as the regular expression is not familiar with, you can refer to this article (regular expression)
Copy Code code as follows:
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's user Agent header:" + ug;
var browsertype = "";
var ver = "";
Detect IE and version
var IE = Ug.match (/msie\s*\d\.\d/); Extracts browser type and version information, note that the match () method returns an array rather than a string
var Isie = check (/msie/);
if (Isie) {
BrowserType = "Internet Explorer";
ver = Ie.join (""). Match (/[0-9]/g). Join ("."); Use the Join () method to convert to a string, then match the match () method to the version information, and then use the join () method to convert to a string
}
Detecting 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 version
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 = "The browser you are using is:" + BrowserType + "<span style= ' padding-left:15px;" > Version for:</span> "+ ver;
}
PS: The user agent information for 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 |