JavaScript code used to determine the browser type and version (with multiple instance codes)

Source: Internet
Author: User

In front-end development of websites, browser compatibility problems have left us in a hurry. Chrome's birth does not know how much trouble we need to add. Browser compatibility is the first problem to be solved by the front-end development framework. To solve the compatibility problem, you must first determine the browser type and version accurately.

JavaScript is the main language for front-end development. We can compile JavaScript programs to determine the browser type and version. There are two methods to determine the browser type in JavaScript: one is to distinguish based on the unique attributes of various browsers, and the other is to judge by analyzing the userAgent attributes of the browser. In many cases, after determining the browser type, you must determine the browser version to handle compatibility issues. However, you can only determine the browser version by analyzing the browser's userAgent.

Let's analyze the features of various browsers and Their userAgent.

IE

Only IE supports the creation of ActiveX controls, so she has something that is not available in other browsers, namely the ActiveXObject function. As long as you determine that the window object has the ActiveXObject function, you can clearly determine that the current browser is IE. The typical userAgent versions of IE are as follows:

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2)
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
Mozilla/4.0 (compatible; MSIE 5.0; Windows NT)

The version number is a number after MSIE.

Firefox

All DOM elements in Firefox have a getBoxObjectFor function to obtain the location and size of the DOM element (IE corresponds to the getBoundingClientRect function ). This is exclusive to Firefox. It can be determined that the current browser is Firefox. The userAgent versions of Firefox are roughly as follows:

Mozilla/5.0 (Windows; U; Windows NT 5.2) Gecko/2008070208 Firefox/3.0.1
Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070309 Firefox/2.0.0.3
Mozilla/5.0 (Windows; U; Windows NT 5.1) Gecko/20070803 Firefox/1.5.0.12
The version number is a number after Firefox.

Opera

Opera provides a special browser flag, that is, the window. opera attribute. The typical userAgent of Opera is as follows:

Opera/9.27 (Windows NT 5.2; U; zh-cn)
Opera/8.0 (Macintosh; PPC Mac OS X; U; en)
Mozilla/5.0 (Macintosh; PPC Mac OS X; U; en) Opera 8.0

The version number is a number near Opera.

Safari

Safari has an openDatabase function that is not available in other browsers and can be used as a flag for judging Safari. The typical userAgent of Safari is as follows:

Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Version/3.1 Safari/525.13
Mozilla/5.0 (iPhone; U; CPU like Mac OS X) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/4A93 Safari/419.3

The Version number is a number after Version.

Chrome

Chrome has a MessageEvent function, but Firefox does. However, Chrome does not have the getBoxObjectFor function of Firefox. Based on this condition, the Chrome browser can be accurately determined. Currently, Chrome's userAgent is:

Mozilla/5.0 (Windows; U; Windows NT 5.2) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13

The version number is only the number after Chrome.

Interestingly, Chrome's userAgent also contains Safari features. Maybe this is the basis for Chrome to run all Apple browser applications.

Once we understand the above information, we can base these features to determine the browser type and version. We will save the judgment results in the Sys namespace and become the basic identifier information of the front-end framework for future programs to read. If a browser is identified, Sys namespace will have an attribute of the browser name, whose value is the version number of the browser. For example, if IE 7.0 is determined, Sys. ie is 7.0; If Firefox 3.0 is determined, Sys. firefox is 3.0. The following code determines the browser:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

We put the IE judgment first, because IE has the most users, followed by Firefox. Judging the browser type in the order of users can improve the judgment efficiency and reduce useless work. We put Chrome in the third judgment because we predict that Chrome will soon become the third-largest browser in the market. When analyzing the browser version, the regular expression is used to extract the version information.

If your JavaScript code is very popular, you can also write the previous judgment Code as follows:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

This simplifies JavaScript code. Of course, the readability is slightly lower, depending on whether you pay attention to efficiency or maintainability.

Different features are used to determine the browser method. Although it is faster than using regular expressions to analyze userAgent, these features may change with the browser version. For example, if a browser has been successful in the market due to its unique features, other browsers may also add this feature to it, so that the unique features of the browser disappear, leading to failure in our judgment. Therefore, it is relatively safe to determine the browser type by parsing the features in userAgent. Besides, to determine the version information, you also need to parse the browser's userAgent.

By analyzing the userAgent information of various browsers, it is not difficult to determine the regular expressions of various browsers and their versions. In addition, the judgment on the browser type and version can be fully integrated. Therefore, we can write the following code:


[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

In this example, "...?" is used. ...:... "To streamline the code. The judgment condition is a value assignment statement that completes Regular Expression matching and result copying, and directly serves as a condition judgment. The subsequent version information only needs to be extracted from the previous matching results, which is a very efficient code.

The above code is pre-developed to build a front-end framework and tested on five browsers. In the future, to judge a browser, you only need to use if (Sys. ie) or if (Sys. to determine the browser version, you only need to use if (Sys. ie = '8. 0 ') or if (Sys. firefox = '3. 0.

The front-end framework project has been started, and everything will be viewed and the results...

The script house editor also compiled several codes for you:

Copy codeThe Code is as follows:
Var Browser = new Object ();
Browser. isMozilla = (typeof document. implementation! = 'Undefined') & (typeof document. implementation. createDocument! = 'Undefined') & (typeof HTMLDocument! = 'Undefined ');
Browser. isIE = window. ActiveXObject? True: false;
Browser. isFirefox = (navigator. userAgent. toLowerCase (). indexOf ("firefox ")! =-1 );
Browser. isSafari = (navigator. userAgent. toLowerCase (). indexOf ("safari ")! =-1 );
Browser. isOpera = (navigator. userAgent. toLowerCase (). indexOf ("opera ")! =-1 );
Function check (){
Alert (Browser. isIE? 'Ie': 'Not ie ');
Alert (Browser. isFirefox? 'Firefox ': 'Not Firefox ');
Alert (Browser. isSafari? 'Safari ': 'Not Safari ');
Alert (Browser. isOpera? 'Opera ': 'Not Opera ');
}
Window. onload = check;

Copy codeThe Code is as follows:
Function isBrowser (){
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;
If (Sys. ie) {// Js judge as ie browser
Alert ('HTTP: // www.jb51.net' + Sys. ie );
If (Sys. ie = '9. 0') {// Js determines it is IE 9
} Else if (Sys. ie = '8. 0') {// Js determines it as IE 8
} Else {
}
}
If (Sys. firefox) {// Js judge as firefox
Alert ('HTTP: // www.jb51.net' + Sys. firefox );
}
If (Sys. chrome) {// Js judge as Google chrome
Alert ('HTTP: // www.jb51.net' + Sys. chrome );
}
If (Sys. opera) {// Js judge as operabrowser
Alert ('HTTP: // www.jb51.net' + Sys. opera );
}
If (Sys. safari) {// Js determines it is an Apple safari browser
Alert ('HTTP: // www.jb51.net' + Sys. safari );
}
}

This article describes how to use jquery to obtain the browser type and version number. The specific jquery code is as follows:

Copy codeThe Code is as follows:
$ (Document). ready (function (){
Varbrow = $. browser;
VarbInfo = "";
If (brow. msie) {bInfo = "MicrosoftInternetExplorer" + brow. version ;}
If (brow. mozilla) {bInfo = "MozillaFirefox" + brow. version ;}
If (brow. safari) {bInfo = "AppleSafari" + brow. version ;}
If (brow. opera) {bInfo = "Opera" + brow. version ;}
Alert (bInfo );
});

JQuery has removed $. browser and $. browser. version from version 1.9 and replaced it with the $. support method. For more information about $. support, see:

JQuery 1.9 replaces $. support with the $. browser method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.