https://github.com/DamonOehlman/detect-browser

detect-browser

This is a package that attempts to detect a browser vendor and version (in a semver compatible format) using a navigator useragent in a browser or process.version in node.

这个包使用浏览器中的navigator useragent或node中的process.version检测浏览器厂商和版本(与semver兼容的格式)

Example Usage

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(browser.version);
console.log(browser.os);
}

Or you can use a switch statement:

const { detect } = require('detect-browser');
const browser = detect(); // handle the case where we don't detect the browser
switch (browser && browser.name) {
case 'chrome':
case 'firefox':
console.log('supported');
break; case 'edge':
console.log('kinda ok');
break; default:
console.log('not supported');
}

看下图控制器第一行的输出我们就能够看见得到的是{name : "chrome",version : "70.0.3538", os : "Mac OS"}


Adding additional browser support

The current list of browsers that can be detected by detect-browser is not exhaustive. If you have a browser that you would like to add support for then please submit a pull request with the implementation.

但是目前能够被detect-browser这个库检测到的浏览器列表还不够详尽。如果你有想要加入的浏览器,那么就请提交一个实现的请求

Creating an acceptable implementation requires two things需要两样东西:

  1. A test demonstrating that the regular expression you have defined identifies your new browser correctly. Examples of this can be found in the test/logic.js file.test测试中阐述了你用来正确识别你的浏览器的自定义的正则表达式,例子如test/logic.js,看下面
  1. Write the actual regex to the index.js file. In most cases adding the regex to the list of existing regexes will be suitable (if usage of detect-brower returns undefined for instance), but in some cases you might have to add it before an existing regex. This would be true for a case where you have a browser that is a specialised variant of an existing browser but is identified as the non-specialised case.在index.js中写下真是的正则表达式。在大多数情况下列表中已存在的正则表达式与添加进的是相配的,但是在一些情况下你就必须要将其添加在已存在的正则表达式之前。如果您的浏览器是现有浏览器的特殊版本,但被识别为非特殊的,那么这种情况就会发生

When writing the regular expression remember that you would write it containing a single capturing group which captures the version number of the browser.

在编写正则表达式时,请记住,您将编写包含捕获浏览器版本号的单个捕获组的表达式

detect-browser/index.js

function detect() {
if (typeof navigator !== 'undefined') {//下面图中有显示navigator
return parseUserAgent(navigator.userAgent);//navigator.userAgent结果为:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
} return getNodeVersion();
} function detectOS(userAgentString) {
var rules = getOperatingSystemRules();//匹配操作系统的正则表达式
var detected = rules.filter(function (os) {
return os.rule && os.rule.test(userAgentString);
})[]; return detected ? detected.name : null;
} function getNodeVersion() {
var isNode = typeof process !== 'undefined' && process.version;
return isNode && {
name: 'node',
version: process.version.slice(),
os: process.platform
};
} function parseUserAgent(userAgentString) {
var browsers = getBrowserRules();//得到浏览器的正则表达式
if (!userAgentString) {
return null;
} var detected = browsers.map(function(browser) {
var match = browser.rule.exec(userAgentString);
var version = match && match[].split(/[._]/).slice(,); if (version && version.length < ) {
version = version.concat(version.length == ? [, ] : []);
} return match && {
name: browser.name,
version: version.join('.')
};
}).filter(Boolean)[] || null; if (detected) {
detected.os = detectOS(userAgentString);
} if (/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/i.test(userAgentString)) {
detected = detected || {};
detected.bot = true;
} return detected;
} function getBrowserRules() { //返回相应的浏览器的正则表达式
return buildRules([
[ 'aol', /AOLShield\/([-\._]+)/ ],
[ 'edge', /Edge\/([-\._]+)/ ],
[ 'yandexbrowser', /YaBrowser\/([-\._]+)/ ],
[ 'vivaldi', /Vivaldi\/([-\.]+)/ ],
[ 'kakaotalk', /KAKAOTALK\s([-\.]+)/ ],
[ 'samsung', /SamsungBrowser\/([-\.]+)/ ],
[ 'chrome', /(?!Chrom.*OPR)Chrom(?:e|ium)\/([-\.]+)(:?\s|$)/ ],
[ 'phantomjs', /PhantomJS\/([-\.]+)(:?\s|$)/ ],
[ 'crios', /CriOS\/([-\.]+)(:?\s|$)/ ],
[ 'firefox', /Firefox\/([-\.]+)(?:\s|$)/ ],
[ 'fxios', /FxiOS\/([-\.]+)/ ],
[ 'opera', /Opera\/([-\.]+)(?:\s|$)/ ],
[ 'opera', /OPR\/([-\.]+)(:?\s|$)$/ ],
[ 'ie', /Trident\/\..*rv\:([-\.]+).*\).*Gecko$/ ],
[ 'ie', /MSIE\s([-\.]+);.*Trident\/[-]./ ],
[ 'ie', /MSIE\s(\.)/ ],
[ 'bb10', /BB10;\sTouch.*Version\/([-\.]+)/ ],
[ 'android', /Android\s([-\.]+)/ ],
[ 'ios', /Version\/([-\._]+).*Mobile.*Safari.*/ ],
[ 'safari', /Version\/([-\._]+).*Safari/ ],
[ 'facebook', /FBAV\/([-\.]+)/],
[ 'instagram', /Instagram\s([-\.]+)/],
[ 'ios-webview', /AppleWebKit\/([-\.]+).*Mobile/]
]);
} function getOperatingSystemRules() {//匹配操作系统的正则表达式
return buildRules([
[ 'iOS', /iP(hone|od|ad)/ ],
[ 'Android OS', /Android/ ],
[ 'BlackBerry OS', /BlackBerry|BB10/ ],
[ 'Windows Mobile', /IEMobile/ ],
[ 'Amazon OS', /Kindle/ ],
[ 'Windows 3.11', /Win16/ ],
[ 'Windows 95', /(Windows )|(Win95)|(Windows_95)/ ],
[ 'Windows 98', /(Windows )|(Win98)/ ],
[ 'Windows 2000', /(Windows NT 5.0)|(Windows )/ ],
[ 'Windows XP', /(Windows NT 5.1)|(Windows XP)/ ],
[ 'Windows Server 2003', /(Windows NT 5.2)/ ],
[ 'Windows Vista', /(Windows NT 6.0)/ ],
[ 'Windows 7', /(Windows NT 6.1)/ ],
[ 'Windows 8', /(Windows NT 6.2)/ ],
[ 'Windows 8.1', /(Windows NT 6.3)/ ],
[ 'Windows 10', /(Windows NT 10.0)/ ],
[ 'Windows ME', /Windows ME/ ],
[ 'Open BSD', /OpenBSD/ ],
[ 'Sun OS', /SunOS/ ],
[ 'Linux', /(Linux)|(X11)/ ],
[ 'Mac OS', /(Mac_PowerPC)|(Macintosh)/ ],
[ 'QNX', /QNX/ ],
[ 'BeOS', /BeOS/ ],
[ 'OS/2', /OS\// ],
[ 'Search Bot', /(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves\/Teoma)|(ia_archiver)/ ]
]);
} function buildRules(ruleTuples) {
return ruleTuples.map(function(tuple) {
return {
name: tuple[],
rule: tuple[]
};
});
} module.exports = {
detect: detect,
detectOS: detectOS,
getNodeVersion: getNodeVersion,
parseUserAgent: parseUserAgent
};

detect-browser/test/logic.js

使用例子来进行说明某类userAgent会检测出什么样的结果:

var test = require('tape');
var { parseUserAgent } = require('../'); function assertAgentString(t, agentString, expectedResult) {
t.deepEqual(parseUserAgent(agentString), expectedResult);
} test('detects Chrome', function(t) {
assertAgentString(t,
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
{ name: 'chrome', version: '50.0.2661', os: 'Linux' }
); assertAgentString(t,
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
{ name: 'chrome', version: '41.0.2228', os: 'Windows 7' }
); t.end();
});
test('handles no browser', function(t) {
assertAgentString(t,
null,
null
); t.end();
});

DamonOehlman/detect-browser的更多相关文章

  1. python flask detect browser language

    python flask detect browser language   No problem. We won't show you that ad again. Why didn't you l ...

  2. C#检测浏览器类型 Detect Browser

    private void Button1_Click(object sender, System.EventArgs e) { System.Web.HttpBrowserCapabilities b ...

  3. clear session on close of browser jsp

    关闭浏览器销毁session <%@ Page Language="C#" AutoEventWireup="true" CodeBehind=" ...

  4. 【CSS3 入门教程系列】CSS3 Media Queries 实现响应式设计

    在 CSS2 中,你可以为不同的媒介设备(如屏幕.打印机)指定专用的样式表,而现在借助 CSS3 的 Media Queries 特性,可以更为有效的实现这个功能.你可以为媒介类型添加某些条件,检测设 ...

  5. 26 个 jQuery使用技巧

    1. 禁用右键点击(Disable right-click) $(document).ready(function(){ $(document).bind("contextmenu" ...

  6. 直接拿来用 九个超实用的PHP代码片段(二)

    每位程序员和开发者都喜欢讨论他们最爱的代码片段,尤其是当PHP开发者花费数个小时为网页编码或创建应用时,他们更知道这些代码的重要性.为了节约编码时间,笔者收集了一些较为实用的代码片段,帮助开发者提高工 ...

  7. 开源网站流量统计系统Piwik源码分析——参数统计(一)

    Piwik现已改名为Matomo,这是一套国外著名的开源网站统计系统,类似于百度统计.Google Analytics等系统.最大的区别就是可以看到其中的源码,这正合我意.因为我一直对统计的系统很好奇 ...

  8. 【JavaScript 封装库】BETA 5.0 测试版发布!

    JavaScript 前端框架(封装库) BETA 5.0 已于10月10日正式发布,今天开始提供 BETA 5.0 的 API 参考文献.相较于之前 5 个版本的发布都是草草的提供源代码,并没有很多 ...

  9. 后端程序员看前端想死(二)进入页面之后js分析

    在上一篇中分析了一下以网页的组成.header中引入的乱七八糟的东西,现在进入到js中进行分析了 tuhooo啊,你是要搞前端了么? nonono,好玩,学一下 打开页面之后执行js的几种方法 直接写 ...

  10. Code Project精彩系列(转)

    Code Project精彩系列(转)   Code Project精彩系列(转)   Applications Crafting a C# forms Editor From scratch htt ...

随机推荐

  1. git入门(廖雪峰老师)

    根据廖雪峰老师的git教程进行学习总结: 1.之前上班用的都是svn进行管理,那么svn和git有什么区别呢? svn是集中式的版本控制系统,而git是分布式版本控制系统,那么集中式和分布式版本控制系 ...

  2. 【Quartz】问题记录注意事项【四】

    记录一:queartz 在同时启动多个任务是,触发器名称不能设置一致,不然第二次启动会不成功 记录二:quartz 在使用任务与触发器分离写法时,任务必须要带(.StoreDurably()) IJo ...

  3. NIO学习笔记四 :SocketChannel 和 ServerSocketChannel

    Java NIO中的SocketChannel是一个连接到TCP网络套接字的通道.可以通过以下2种方式创建SocketChannel: 打开一个SocketChannel并连接到互联网上的某台服务器. ...

  4. Python全栈学习_day005知识点

    今日内容大纲: . 字典的增删改查以及其他操作 . 字典的嵌套 . 字典的增删改查以及其他操作 , 'sex': '男'}, 'name_list': ['无双', 'alex', 'BlameK'] ...

  5. mysql 5.7 线程阻塞处理

    出现的错误: ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction 解决办法: 查看sleep的进程 m ...

  6. SQL Anywhere5.5: Metadata

    http://dcx.sybase.com/1101/en/dbprogramming_en11/ianywhere-data-sqlanywhere-saconnection-getschem633 ...

  7. 解决element-ui的el-select组件文字超过宽度时不出现横向滚动条问题

    我用的element-ui是V1.4.3. 目前遇到一个问题,在用el-select组件的时候,当选项的内容很长的时候,会撑开下拉菜单的宽度,这样影响美观.具体如下图所示: 解决这个问题的思路:设置下 ...

  8. form的重置reset

    HTML中Form表单的reset方法被用来重置用户所输入的内容,以前一直误以为其是单纯的将input等输入项中的值清空. 但实际上不是这样的,reset方法的本质是将input等输入项中的内容还原为 ...

  9. 我的Java之旅 第三课 从Applet到JSP

    一.Applet   Applet是一种特殊的Java程序,它本身不能单独运行(因为本身没有main()),需要嵌入在一个HTML文件中,借助浏览器或者appletviewer来解释执行.   App ...

  10. 使用CLion在MacOS、Linux上编译C++代码

    推荐: http://www.cnblogs.com/conorpai/p/6425048.html