search
HomeWeb Front-endJS Tutorialjs code to determine browser type and version (with multiple example codes)_javascript skills

In website front-end development, browser compatibility issues have already made us in a hurry. The birth of Chrome will cause us more troubles. Browser compatibility is the first problem to be solved by the front-end development framework. To solve the compatibility problem, you must first accurately determine the browser type and its version.

JavaScript is the main language for front-end development. We can determine the type and version of the browser by writing JavaScript programs. There are generally two methods for JavaScript to determine the browser type. One is based on the unique attributes of various browsers, and the other is determined by analyzing the userAgent attribute of the browser. In many cases, after the browser type is determined by value, the browser version needs to be determined to handle compatibility issues, and the browser version can generally only be known by analyzing the browser's userAgent.

Let’s first analyze the characteristics of various browsers and their userAgents.

IE

Only IE supports creating ActiveX controls, so it has something that other browsers don’t have, which is the ActiveXObject function. As long as it is determined that the ActiveXObject function exists in the window object, it can be clearly determined that the current browser is IE. The typical userAgent for each version of IE is 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)

Among them, the version number is the number after MSIE.

Firefox

Every DOM element in Firefox has a getBoxObjectFor function, which is used to obtain the position and size of the DOM element (the corresponding function in IE is the getBoundingClientRect function). This is unique to Firefox. By judging it, you can know that the current browser is Firefox. The userAgents of several 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
Where, the version number is the number after Firefox.

Opera

Opera provides a special browser flag, which is the window.opera attribute. 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 a number close to Opera.

Safari

Safari browser has an openDatabase function that other browsers do not have, which can be used as a sign to judge Safari. A typical Safari 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 so does Firefox. However, fortunately, Chrome does not have the getBoxObjectFor function of Firefox. According to this condition, the Chrome browser can still 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

Among them, the version number is only the number after Chrome.

Interestingly, Chrome’s userAgent also includes Safari features. Perhaps this is the basis for Chrome to run all Apple browser applications.

As long as we understand the above information, we can determine the browser type and its version based on these characteristics. We will save the judgment results in the Sys namespace and become the basic flag information of the front-end framework for future programs to read. If the browser is determined, the Sys namespace will have an attribute of the browser name, and its value is the version number of the browser. For example, if IE 7.0 is determined, the value of Sys.ie is 7.0; if Firefox 3.0 is determined, the value of Sys.firefox is 3.0. The following is the code to determine the browser:


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

我们把对IE的判断放在第一,因为IE的用户最多,其次是判断Firefox。按使用者多少的顺序来判断浏览器类型,可以提高判断效率,少做无用功。之所以将Chrome放在第三判断,是因为我们预测Chrome很快会成为市场占有率第三的浏览器。其中,在分析浏览器版本时,用到了正则表达式来析取其中的版本信息。

如果你的JavaScript玩得很高,你还可以将前面的判断代码写成这样:


[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

这样可以使JavaScript代码更精简些。当然,可读性稍差一些,就看你是重视效率还是重视可维护性了。

使用不同特征来判断浏览器的方法,虽然在速度上比用正则表达式分析userAgent要来的快,不过这些特征可能会随浏览器版本而变化。比如,一种浏览器本来独有的特性取得了市场上的成功,其他浏览器也就可能跟着加入该特性,从而使该浏览器的独有特征消失,导致我们的判断失败。因此,相对比较保险的做法是通过解析userAgent中的特征来判断浏览器类型。何况,反正判断版本信息也需要解析浏览器的userAgent的。

通过分析各类浏览器的userAgent信息,不难得出分辨各类浏览器及其版本的正则表达式。而且,对浏览器类型的判断和版本的判断完全可以合为一体地进行。于是,我们可以写出下面的代码:


[Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]

其中,采用了“... ? ... : ...”这样的判断表达式来精简代码。判断条件是一条赋值语句,既完成正则表达式的匹配及结果复制,又直接作为条件判断。而随后的版本信息只需从前面的匹配结果中提取即可,这是非常高效的代码。

以上的代码都是为了打造前端框架所做的预研,并在五大浏览器上测试通过。今后,判断某种浏览器只需用if(Sys.ie)或if(Sys.firefox)等形式,而判断浏览器版本只需用if(Sys.ie == '8.0')或if(Sys.firefox == '3.0')等形式,表达起来还是非常优雅的。

前端框架项目已经启动,一切就看过程和结果了...

脚本之家小编又为大家整理了几个代码:

复制代码 代码如下:

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;

复制代码 代码如下:

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 determines that it is IE browser
alert('http://www.jb51.net' Sys.ie);
if(Sys. ie=='9.0'){//Js is judged to be IE 9
}else if(Sys.ie=='8.0'){//Js is judged to be IE 8
}else{
}
}
if(Sys.firefox){//Js determines it is Firefox browser
alert('http://www.jb51.net' Sys.firefox);
}
if(Sys.chrome){//Js determines it is Google chrome browser
alert('http://www.jb51.net' Sys.chrome);
}
if(Sys. opera){//Js judgment is opera browser
alert('http://www.jb51.net' Sys.opera);
}
if(Sys.safari){//Js judgment For Apple safari browser
alert('http://www.jb51.net' Sys.safari);
}
}

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

Copy code The 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 Starting from version 1.9, $.browser and $.browser.version have been removed and replaced by the $.support method. If you need to know about $.support, please refer to:

jQuery 1.9 uses $.support instead of $.browser method

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment