The checkBrowser() function below mainly detects three browsers (IE, firefox, chrome). Friends who are interested in detecting other browsers can add detection codes by themselves!
HTML part code: (Execute detection function when the page is loaded)
javascript part code:
The detection principle is mainly based on extracting the browser and type and version information from the browser's user agent header nanigator.userAgent. Regular expressions can easily meet our needs. If you are not familiar with regular expressions, you can refer to this article (
Regular Expressions)
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 (/msies*d.d/); //Extract 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("."); //Use join( first ) method into a string, then use the match() method to match the version information, and then use the join() method to convert it into a 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 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 "Version: " 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 |