JS to determine the browser type, version of the code (with multiple instance code) _javascript Tips

Source: Internet
Author: User

In the front-end development of the Web site, browser compatibility problem has let us rush, the birth of Chrome did not know to give us a lot of trouble. Browser compatibility is the first problem to be solved by the front-end development framework, in order to solve the compatibility problem, we must first accurately determine the browser type and its version.

JavaScript is the primary language for front-end development, and we can write JavaScript programs to determine the type and version of the browser. JavaScript can determine browser types in general there are two ways, one is based on a variety of browser-specific properties to distinguish, the other is by analyzing the browser's useragent properties to judge. In many cases, after the value is judged by the browser type, it is also necessary to judge the browser version to handle the compatibility issue, and to judge the browser version is generally only through the analysis of the browser useragent to know.

Let's first analyze the features and useragent of various browsers.

Ie

Only IE supports the creation of ActiveX controls, so she has something that other browsers do not have, that is, the ActiveXObject function. As long as you judge the Window object exists ActiveXObject function, you can clearly determine the current browser is ie. The typical useragent of IE versions 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)

Where the version number is the number after the MSIE.

Firefox

The DOM elements in Firefox have a getboxobjectfor function to get the position and size of the DOM element (ie corresponds to the getboundingclientrect function). This is unique to Firefox, judge it can know is the current browser is Firefox. Firefox several versions of the useragent 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
Where the version number is the number after Firefox.

Opera

Opera offers a special browser flag, which is the Window.opera property. Opera's typical useragent 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

Among them, the version number is close to opera's number.

Safari

Safari browser has a opendatabase function that is not available in other browsers and can be used as a marker for safari. Safari's typical useragent 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 the number after version.

Chrome

Chrome has a messageevent function, but Firefox does. However, the good news is that Chrome does not have Firefox's getboxobjectfor function, which can be used to accurately determine the Chrome browser. At present, the useragent of Chrome is:

mozilla/5.0 (Windows; U Windows NT 5.2) applewebkit/525.13 (khtml, like Gecko) chrome/0.2.149.27 safari/525.13

Where the version number is in Chrome only after the number.

Interestingly, Chrome's useragent also includes Safari features, which is perhaps the basis for all of the apps that Chrome can run on Apple's browser.

As soon as we know the above information, we can base these features on the browser type and its version. We will keep the result of the judgment in the Sys namespace, as the basic information of the front-end framework, for future programs to read. If you judge a browser, the Sys namespace will have a property of that browser name, and its value is the version number of the browser. For example, if you judge IE 7.0, the value of sys.ie is 7.0, and if you Judge Firefox 3.0, the Sys.firefox value is 3.0. Here is the code to judge the browser:

<textarea id="runcode2552"><script type= "Text/javascript" > var Sys = {}; var ua = Navigator.userAgent.toLowerCase (); if (window. ActiveXObject) sys.ie = Ua.match (/msie ([\d.] +)/) [1] else if (document.getboxobjectfor) Sys.firefox = Ua.match (/firefox\/([\d.] +)/) [1] else if (window. Messageevent &&!document.getboxobjectfor) sys.chrome = Ua.match (/chrome\/([\d.] +)/) [1] else if (window.opera) Sys.opera = Ua.match (/opera. ( [\d.] +)/) [1] else if (window.opendatabase) Sys.safari = Ua.match (/version\/([\d.] +)/) [1]; The following tests 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></textarea>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

We put the judgment of IE on the first, because IE users the most, followed by the judgement of Firefox. According to the number of users to determine the type of browser, you can improve the efficiency of judgment, less do not work hard. The reason we put Chrome on the third judgment is because we predict that Chrome will soon become the third-most-market-share browser. In the analysis of the browser version, a regular expression is used to extract the version information.

If your JavaScript is playing high, you can also write the previous judgment code like this:

<textarea id="runcode94266"><script type= "Text/javascript" > var Sys = {}; var ua = navigator.userAgent.toLowerCase (); window. ActiveXObject? sys.ie = Ua.match (/msie ([\d.] +/) [1]: Document.getboxobjectfor? Sys.firefox = Ua.match (/firefox\/([\d.] (+)/) [1]: window. Messageevent &&!document.getboxobjectfor? Sys.chrome = Ua.match (/chrome\/([\d.] +/) [1]: Window.opera? Sys.opera = Ua.match (/opera. ( [\d.] +/) [1]: Window.opendatabase? Sys.safari = Ua.match (/version\/([\d.] +)/) [1]: 0; The following tests liehuo.net 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></textarea>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

This will make the JavaScript code a little more streamlined. Of course, a little less readable, it depends on whether you pay attention to efficiency or maintainability.

Using different features to judge the browser's approach, although useragent is faster than the regular expression analysis, these features may change with the browser version. For example, a browser-specific feature has been successful in the marketplace, and other browsers may be able to join the feature, so that the browser's unique features disappear, resulting in our judgment failure. Therefore, the relative insurance approach is to determine the browser type by parsing the features in the useragent. Moreover, the judgment version information also needs to parse the browser the useragent.

By analyzing the useragent information of various browsers, it is not difficult to distinguish regular expressions of various browsers and their versions. Moreover, the judgment of the browser type and the judgement of the version can be integrated into one. So, we can write the following code:

<textarea id="runcode72240"><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; The following tests liehuo.net 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></textarea>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Among them, the adoption of the "...? ..:... "Such a judgment expression to streamline the code. The judgment condition is an assignment statement, which completes the matching of regular expression and the result copy, and is directly used as the condition judgment. And then the version of the information can only be extracted from the previous matching results, this is very efficient code.

The above code is designed to build the front-end framework for the research, and in the five major browsers to test the pass. In the future, it is very elegant to judge that a browser only uses the form of if (sys.ie) or if (Sys.firefox), and that the browser version only needs to be expressed in the form of if (sys.ie = ' 8.0 ') or if (Sys.firefox = = ' 3.0 ').

The front end frame project has been started, and everything depends on the process and results ...

Cloud Habitat Community Small series and for everyone to organize a few code:

Copy Code code 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 Code code 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 is judged as IE browser
Alert (' http://www.jb51.net ' +sys.ie);
if (sys.ie== ' 9.0 ') {//js is judged IE 9
}else if (sys.ie== ' 8.0 ') {//js is judged IE 8
}else{
}
}
if (Sys.firefox) {//js is judged to be Firefox (Firefox) browser
Alert (' http://www.jb51.net ' +sys.firefox);
}
if (sys.chrome) {//js judged as Google Chrome browser
Alert (' http://www.jb51.net ' +sys.chrome);
}
if (Sys.opera) {//js is judged as Opera browser
Alert (' http://www.jb51.net ' +sys.opera);
}
if (Sys.safari) {//js judged as Apple Safari browser
Alert (' http://www.jb51.net ' +sys.safari);
}
}

Share a function method to get the browser type and browser version number through jquery. The specific jquery code is as follows:

Copy Code code 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 starts with version 1.9, removing $.browser and $.browser.version and replacing it with the $.support method, if you need to know $.support please refer to:

JQuery 1.9 uses the $.support alternative $.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.