Javascript efficiently identifies the browser type and version

Source: Internet
Author: User

<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;

// Perform 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>

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.

Then change the browser to preview the effect.

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.