您的位置:首页 > Web前端 > JavaScript

使用JavaScript检测浏览器

2015-09-12 19:16 701 查看
假设你真的需要检测浏览器的类型,使用JavaScript非常easy达到。





View
Demo

Download
Source from GitHub

JavaScript有一个navigator的标准对象,它包括了关于浏览器使用的信息。

navigator对象由非常多属性。可是userAgent属性---一个字符串就已经包括了浏览器、操作系统以及其他我们须要的全部信息。

假设须要显示
navigator.userAgent
的值。仅仅须要选择以下的一种的方式就能够:

Alert

// Display in an alert box
alert(navigator.userAgent);




火狐30在win7上的navigator.userAgent值。

Document.write

// Write it in the HTML document
document.write(navigator.userAgent);


console.log

// Display it in the browser's developer tool
// This is ideal
// Use console.log() when you're developing/experimenting JavaScript
console.log(navigator.userAgent);


对于IE11,输出例如以下

Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MASM; .NET4.0C; .NET4.0E; rv:11.0) like Gecko


正如你看到的。使用userAgent.navigator的问题在于。它是一串非常长的字符串,而且可读性不好。

所以。假设我想得到想要的信息,或者把它给用户看,我首先,我要解析这个字符串。问题是我对于正則表達式的使用(在其它一些方面)显得无能为力。所以我非常乐意使用Darcy Clarke写的Detect.js JavaScript 程序库。

Detect.js可以将一个字符串解析为一个可读和可操作的JavaScript对象。为了显示浏览器的名称、版本号以及所用的操作系统,可參考例如以下代码:

// Create 'user' object that will contain Detect.js stuff
// Call detect.parse() with navigator.userAgent as the argument
var user = detect.parse(navigator.userAgent);

// Display some property values in my browser's dev tools console
console.log(
user.browser.family
user.browser.version
user.os.name
);



Firebug, 将看到:

Firefox 30 Windows 7




同一台机器上。在Google开发人员工具中的结果是:

Chrome 35 Windows 7




能够使用条件语句来针对一个特定的浏览器,比如:仅仅想针对Safari桌面浏览器

if (user.browser.family === 'Safari') {
alert('You\'re using the Safari browser');
}




全部被解析过的属性表:



注意:假设属性不能被解析,则其值为null或者undefined。假设你想把这些信息给你的用户看,那么你就应该对于可能出现null或者undefined的值地方条件推断。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: