`
天梯梦
  • 浏览: 13747417 次
  • 性别: Icon_minigender_2
  • 来自: 洛杉矶
社区版块
存档分类
最新评论

JavaScript判断浏览器 Browser detect

 
阅读更多

The script

Copy this script into your JavaScript files. It works immediately, and you can query three properties of the BrowserDetect object:

//Browser name: 
BrowserDetect.browser
    
//Browser version: 
BrowserDetect.version
    
//OS name: 
BrowserDetect.OS

 

代码:

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera",
			versionSearch: "Version"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

//alert(BrowserDetect.browser);

 

This script will only continue to work if you regularly check whether newer browsers still follow the rules set forth in the dataBrowser and dataOS arrays.

 

Browser detection

The dataBrowser array is filled with objects that contain the properties that help the script detect your users' browser. Note its general syntax:

dataBrowser: [
	{
		prop: window.opera,
		identity: "Opera",
		versionSearch: "Version" // note: no comma
	},
	{
		string: navigator.userAgent,
		subString: "MSIE",
		identity: "Explorer",
		versionSearch: "MSIE" // note: no comma
	} // note: no comma
];

 

The [] define an array literal, and all of its elements are object literals. Each object literal is enclosed in curly braces {} and contains a few properties (name: value,). Note that a comma between the objects and between the properties is required, but that the last comma is always forbidden.

 

Properties

Every object in the dataBrowser array can contain the following properties:

  1. string and subString properties. These say: "search for subString in string". If the subString is found, the browser is identified.
  2. a prop property. It says "see if prop is supported". If it is, the browser is identified.
  3. an identity string. This string becomes the value of BrowserDetect.browser.
  4. a versionSearch string. This is for searching for the version number (see below). If this property is absent, the identity string is used instead.

Every object must contain either 1 or 2 (never both!), must contain 3 and may contain 4.

 

Example: Safari

As an example, here's the Safari object:

{
	string: navigator.vendor,
	subString: "Apple",
	identity: "Safari"
},

 

The script takes the value of navigator.vendor and sees if it contains the string "Apple". If it does, BrowserDetect.browser is set to "Safari" and the browser detection quits. If it doesn't, the script moves on to the next object.

 

Example: Opera

The next object is Opera:

{
	prop: window.opera,
	identity: "Opera",
	versionSearch: "Version"
},

 

Here the script checks if the property window.opera exists. If it does, BrowserDetect.browser is set to "Opera". If it doesn't, the script moves on to the next object.

 

If the browser turns out to be Opera the script looks for version information after the "Version" string.

 

userAgent and vendor

The trick of browser detection is knowing where to look for the information you need. Traditionally we use navigator.userAgent. However, precisely because this check is traditional many minor browsers change their navigator.userAgent string so that bad detects written by amateur web developers are fooled into identifying it as Explorer. Section 3D of the book discusses this problem, as well as some gory details of navigator.userAgent.

 

More recently, new browsers have started to support the navigator.vendor property, which contains information about the vendor. In general I prefer to use this string for my detection, since it's less contaminated by obfuscation.

 

Of course, as soon as amateurs start using my detection script to detect Safari, Opera, Konqueror or other browsers, the browser vendors will be forced to change the value of navigator.vendor and my detect will not work any more.

 

Detection order

The objects in dataBrowser are used in the order they appear; that's why dataBrowser is an array. As soon as a positive identification is made the script ends, and it doesn't check the remaining objects.

Detection order is very important. The general rule is that you check for the minor browsers first. The reason is that many minor browsers give their users the opportunity to change identity in order to work around browser detects.

 

For instance, the Opera navigator.userAgent may contain "MSIE". If we'd check for Explorer first, we'd find the "MSIE" and would incorrectly conclude that the browser is Explorer. In order to avoid this false detection, we should check for Opera first. If the browser is in fact Opera, the script never proceeds to the "MSIE" check.

 

Safari's navigator.userAgent also contains "Gecko". This causes the same problem: a check for Mozilla would reveal "Gecko", and Safari would be identified as Mozilla. Therefore the Mozilla check only takes place if the browser is not Safari.

 

If you add a new object to detect a new browser, always add it before the Explorer/Mozilla objects at the end of the array.

 

Version number

In general, the version number of a browser can be found directly after its name in navigator.userAgent. The script searches for this name and takes the number that appears after it. For instance, this is Konqueror's navigator.userAgent:

Mozilla/5.0 (compatible; Konqueror/3; Linux)

 

The script searches for the string "Konqueror", skips the next character, and takes the number after that. This is the version number. The script uses parseFloat, so that decimal places in the version number also become part of BrowserDetect.version.

 

Unfortunately Safari's string never contains its official version; only its internal Apple version number (ie. not 1.3.2 but 312.6). Therefore the version number detect doesn't work in Safari. Since this is clearly Apple's fault (it doesn't follow established conventions), I don't care.

 

versionSearch

In general, the browser name as it appears in navigator.userAgent is the same as the identification string. If the browser is "iCab", the script searches for "iCab".

 

However, Explorer needs "MSIE", Mozilla needs "rv", and older Netscape versions need "Mozilla". In order to accomodate these problems you may add a versionSearch property to the browser object. If it's there it's used for the version detect; if it's not there the identity string is used instead.

 

Take the Firefox and Explorer objects:

{
	string: navigator.userAgent,
	subString: "Firefox",
	identity: "Firefox"
},
{
	string: navigator.userAgent,
	subString: "MSIE",
	identity: "Explorer",
	versionSearch: "MSIE"
},

 

If the browser is Firefox, the script should look for the "Firefox" string. Since this is also the browser identity string, a special versionSearch is not necessary.

 

Explorer, however, puts its version number after the string "MSIE". Since I use "Explorer" as identity string, I have to define the versionSearch property as "MSIE".

 

userAgent and appVersion

The version detect script searches for the browser name in both navigator.userAgent and navigator.appVersion. The reason is iCab: this browser's navigator.userAgent may not contain the string "iCab", but navigator.appVersion always does.

 

Operating system

The OS detect works the same as the browser detect. Currently all my OS detects use navigator.platform, since this property appears to always contain the correct information.

 

navigator

Below you see the objects contained by the object navigator. These variables can be read out and give information about the browser and computer of your users. Use this information to add new objects to the browser detect.

navigator.userAgent = Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:20.0) Gecko/20100101 Firefox/20.0
navigator.vendor = 
navigator.platform = MacIntel
navigator.appCodeName = Mozilla
navigator.appName = Netscape
navigator.appVersion = 5.0 (Macintosh)
navigator.language = en-US
navigator.mimeTypes = [object MimeTypeArray]
navigator.oscpu = Intel Mac OS X 10.6
navigator.vendorSub = 
navigator.product = Gecko
navigator.productSub = 20100101
navigator.plugins = [object PluginArray]
navigator.cookieEnabled = true
navigator.onLine = true
navigator.buildID = 20130326150557
navigator.doNotTrack = unspecified
navigator.mozPower = null
navigator.javaEnabled = function javaEnabled() {
    [native code]
}
navigator.taintEnabled = function taintEnabled() {
    [native code]
}
navigator.vibrate = function vibrate() {
    [native code]
}
navigator.addIdleObserver = function addIdleObserver() {
    [native code]
}
navigator.removeIdleObserver = function removeIdleObserver() {
    [native code]
}
navigator.requestWakeLock = function requestWakeLock() {
    [native code]
}
navigator.getDeviceStorage = function getDeviceStorage() {
    [native code]
}
navigator.geolocation = [object GeoGeolocation]
navigator.registerContentHandler = function registerContentHandler() {
    [native code]
}
navigator.registerProtocolHandler = function registerProtocolHandler() {
    [native code]
}
navigator.mozIsLocallyAvailable = function mozIsLocallyAvailable() {
    [native code]
}
navigator.battery = [object BatteryManager]
navigator.mozSms = null
navigator.mozGetUserMediaDevices = function mozGetUserMediaDevices() {
    [native code]
}
navigator.mozGetUserMedia = function mozGetUserMedia() {
    [native code]
}
navigator.mozConnection = [object MozConnection]
navigator.mozCameras = null

 

from: http://www.quirksmode.org/js/detect.html

 

关联:

1.判断来访者所用设备是iPhone、iPad或者电脑(PC)

2. php 检测浏览器版本和操作系统

3. PHP 判断用户语言跳转网页

4. PHP判断浏览器类型和浏览器语言(附各国语言简写代码)

 

 

 

 

分享到:
评论

相关推荐

    javascript获取浏览器相关属性

    这段代码首先定义了一个名为`detectBrowser`的函数,用于检测浏览器类型。通过检查`navigator.userAgent`字符串中是否包含特定的关键字,如`msie`、`firefox`等,来判断浏览器类型。然后根据检测结果,使用`document...

    js判断浏览器类型

    通常,这样的工具库会提供一个封装好的方法,用于简化浏览器类型判断,比如`detectBrowser()`。 总的来说,JavaScript提供多种方式来判断浏览器类型,但应优先考虑特性检测。在实际开发中,理解`navigator`对象及其...

    vue-browser-detect-plugin:Vue浏览器检测插件

    npm install vue-browser-detect-plugin 在您的main.js: import browserDetect from " vue-browser-detect-plugin " ; Vue.use(browserDetect) ; 用法 浏览器信息: vm。$ browserDetect.isIE boolean vm。$ ...

    JS判断浏览器之Navigator对象.pdf

    ### JS判断浏览器之Navigator对象 #### 一、Navigator对象简介 在JavaScript中,`navigator`对象提供了关于用户浏览器的信息。这个对象包含了多个属性,能够帮助开发者了解用户的浏览器类型及其版本等重要信息。这...

    browser-detect:简化检测您的浏览器

    script src =" node_modules/browser-detect/dist/browser-detect.umd.js " &gt; &lt;/ script &gt; const result = browserDetect ( ) ; console . log ( result ) ; 输出 { name : 'chrome' , version : '...

    browser-detect-[removed]使用JavaScript获取浏览器和操作系统信息的技术

    使用JavaScript进行浏览器...本教程描述了JavaScript浏览器检测的两种方法: 显示navigator.UserAgent的字符串值 使用 JavaScript库 阅读《本》中的以获得完整的解释,并了解为什么不应该使用JavaScript浏览器检测。

    javascript 检测浏览器类型和版本的代码.docx

    ### JavaScript检测浏览器类型和版本的方法 #### 一、概述 在Web开发中,有时需要根据用户的浏览器类型或版本来提供不同的功能或体验。这可以通过多种方式实现,其中两种常用的方法为**对象/特征检测法**与**User-...

    detect-browser:从useragent字符串解压缩浏览器类型和版本

    const { detect } = require ( 'detect-browser' ) ; const browser = detect ( ) ; // handle the case where we don't detect the browser if ( browser ) { console . log ( browser . name ) ; console . log ...

    基于js实现判断浏览器类型代码实例

    这个`detectBrowser`函数会根据`User-Agent`字符串判断出用户使用的浏览器类型并打印出来。 需要注意的是,`User-Agent`字符串可能会被篡改,因此这种方法并不能100%准确。但是,在大多数情况下,这足以满足日常...

    javascript经典特效---按浏览器选择背景音乐.rar

    // 假设detectBrowser()是一个检测浏览器的函数 playBackgroundMusic(browser); ``` 这个压缩包中的“按浏览器选择背景音乐.htm”文件很可能包含了上述逻辑的实现。通过分析这个文件,我们可以学习如何在实践中...

    detectOS.js:JavaScript上流行的操作系统和浏览器的简单定义

    console.log("We know your browser – it's " + Detect.browser + " " + Detect.version); console.log("We know your OS – it's " + Detect.OS); console.log("We know everything about you."); 演示版 在上

    react-browser-support:一个React组件,根据您提供的浏览器列表(和最低版本)指示是否支持该浏览器

    React浏览器支持 如果不支持当前的浏览器,则此组件将显示一条消息。...import BrowserSupport , { detectBrowser } from 'react-browser-support' const minBrowserVersions = { chrome : '4.10' , edge : '6' ,

    Using Modernizr to detect HTML5 and CSS3 browser support

    与传统的浏览器嗅探方法相比,Modernizr通过执行一系列测试来判断浏览器是否具备所需功能,这种方法更为准确且高效。目前,Modernizr可以检测超过18种CSS3特性和40多种与HTML5相关的功能。 二、Modernizr的工作机制...

    JS判断浏览器之Navigator对象

    function detectBrowser() { var browser = navigator.appName; var b_version = navigator.appVersion; var version = parseFloat(b_version); if ((browser == "Netscape" || browser == "Microsoft Internet ...

    前端项目-Detect.js.zip

    Detect.js是一款专为前端项目设计的JavaScript库,它通过解析用户代理(User Agent)字符串,帮助开发者准确识别用户的浏览器、操作系统和设备信息,从而实现更精细的前端优化和兼容性处理。 Detect.js库的核心功能...

    detect zoom

    "Detect Zoom" 是一个专门用于检测浏览器缩放比例的JavaScript库,它能够帮助开发者获取精确的缩放信息,从而优化网页在不同缩放级别下的显示效果。本文将深入探讨这个话题,并介绍与"Detect Zoom"相关的知识点。 ...

    DetectInApp检测移动设备的浏览器或应用内信息

    例如,`DetectInApp.browser` 可能返回浏览器信息,而 `DetectInApp.os` 可能返回操作系统信息。对于具体用法,可参考库的源代码f2etw-detect-inapp-b82a67e或其配套的文档。 总的来说,DetectInApp 是一个强大的...

    device-detect:用于检查用户代理是否返回设备和浏览器的 JavaScript 模块

    设备检测JavaScript 模块检查用户代理是否返回设备和浏览器。安装 npm install device - detect -- save - dev用 var deviceDetect = require ( 'device-detect' ) ( ) ;// return all device and browser ...

    js解析url并判断火狐IE浏览器

    本文将详细介绍如何利用JS来解析URL,并判断用户所使用的浏览器是否为火狐或IE。 #### 一、解析URL 在Web开发中,经常需要对URL进行解析以获取其中的特定部分,例如主机名、路径等。在JS中,可以通过`URL`对象来...

Global site tag (gtag.js) - Google Analytics