Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Useragent parser for Node.js, ported from browserscope.org

License

NotificationsYou must be signed in to change notification settings

3rd-Eden/useragent

Repository files navigation

Useragent originated as port ofbrowserscope.org's user agentparser project also known as ua-parser. Useragent allows you to parse user agentstrings with highperformance and accuracy by usinghand tuned regular expressions forbrowser matching. This database is needed to ensure that every browser iscorrectly parsed as every browser vendor implements it's own user agent schema.This is why regular user agent parsers have major issues because they willmost likely parse out the wrong browser name or confuse the render engine versionwith the actual version of the browser.


Build statusBuildStatus


High performance

The module has been developed with a benchmark driven approach. It has apre-compiled library that contains all the Regular Expressions and uses deferredor on demand parsing for Operating System and device information. All thisengineering effort has been worth it asthis benchmark shows:

Starting the benchmark, parsing 62 useragent strings per runExecuted benchmark against node module: "useragent"Count (61), Cycles (5), Elapsed (5.559), Hz (1141.3739447904327)Executed benchmark against node module: "useragent_parser"Count (29), Cycles (3), Elapsed (5.448), Hz (545.6817291171243)Executed benchmark against node module: "useragent-parser"Count (16), Cycles (4), Elapsed (5.48), Hz (304.5373431830105)Executed benchmark against node module: "ua-parser"Count (54), Cycles (3), Elapsed (5.512), Hz (1018.7561434659247)Module: "useragent" is the user agent fastest parser.

Hand tuned regular expressions

This module relies onuap-core'sregexes.yaml user agent database to parse user agent strings.

This database is up-to-date thanks tocontributors such as you. Feel free to submitissues andpull requests.


Installation

Installation is done using the Node Package Manager (NPM). If you don't haveNPM installed on your system you can download it fromnpmjs.org

npm install useragent --save

The--save flag tells NPM to automatically add it to yourpackage.json file.


API

Include theuseragent parser in you node.js application:

varuseragent=require('useragent');

Theuseragent library allows you do use the automatically installed RegExplibrary or you can fetch it live from the remote servers. So if you areparanoid and always want your RegExp library to be up to date to match withagent the widest range ofuseragent strings you can do:

varuseragent=require('useragent');useragent(true);

This will async load the database from the server and compile it to a properJavaScript supported format. If it fails to compile or load it from the remotelocation it will just fall back silently to the shipped version. If you want touse this feature you need to addyamlparser andrequest to your package.json

npm install yamlparser --savenpm install request --save

useragent.parse(useragent string[, js useragent]);

This is the actual user agent parser, this is where all the magic is happening.The function accepts 2 arguments, both should be astring. The first argumentshould the user agent string that is known on the server from thereq.headers.useragent header. The other argument is optional and should bethe user agent string that you see in the browser, this can be send from thebrowser using a xhr request or something like this. This allows you detect ifthe user is browsing the web using theChrome Frame extension.

The parser returns a Agent instance, this allows you to output user agentinformation in different predefined formats. See the Agent section for moreinformation.

varagent=useragent.parse(req.headers['user-agent']);// example for parsing both the useragent header and a optional js useragentvaragent2=useragent.parse(req.headers['user-agent'],req.query.jsuseragent);

The parse method returns aAgent instance which contains all details about theuser agent. See the Agent section of the API documentation for the availablemethods.

useragent.lookup(useragent string[, js useragent]);

This provides the same functionality as above, but it caches the user agentstring and it's parsed result in memory to provide faster lookups in thefuture. This can be handy if you expect to parse a lot of user agent strings.

It uses the same arguments as theuseragent.parse method and returns exactlythe same result, but it's just cached.

varagent=useragent.lookup(req.headers['user-agent']);

And this is a serious performance improvement as shown in this benchmark:

Executed benchmark against method: "useragent.parse"Count (49), Cycles (3), Elapsed (5.534), Hz (947.6844321931629)Executed benchmark against method: "useragent.lookup"Count (11758), Cycles (3), Elapsed (5.395), Hz (229352.03831239208)

useragent.fromJSON(obj);

Transforms the JSON representation of aAgent instance back in to a workingAgent instance

varagent=useragent.parse(req.headers['user-agent']),another=useragent.fromJSON(JSON.stringify(agent));console.log(agent==another);

useragent.is(useragent string).browsername;

This api provides you with a quick and dirty browser lookup. The underlyingcode is usually found on client side scripts so it's not the same quality asouruseragent.parse method but it might be needed for legacy reasons.

useragent.is returns a object with potential matched browser names

useragent.is(req.headers['user-agent']).firefox// trueuseragent.is(req.headers['user-agent']).safari// falsevarua=useragent.is(req.headers['user-agent'])// the object{  version:'3'  webkit:false  opera:false  ie:false  chrome:false  safari:false  mobile_safari:false  firefox:true  mozilla:true  android:false}

Agents, OperatingSystem and Device instances

Most of the methods mentioned above return a Agent instance. The Agent exposesthe parsed out information from the user agent strings. This allows us toextend the agent with more methods that do not necessarily need to be in thecore agent instance, allowing us to expose a plugin interface for third partydevelopers and at the same time create a uniform interface for all versioning.

The Agent has the following property

  • family The browser family, or browser name, it defaults to Other.
  • major The major version number of the family, it defaults to 0.
  • minor The minor version number of the family, it defaults to 0.
  • patch The patch version number of the family, it defaults to 0.

In addition to the properties mentioned above, it also has 2 special properties,which are:

  • os OperatingSystem instance
  • device Device instance

When you access those 2 properties the agent will do on demand parsing of theOperating System or/and Device information.

The OperatingSystem has the same properties as the Agent, for the Device wedon't have any versioning information available, so only thefamily property isset there. If we cannot find the family, they will default toOther.

The following methods are available:

Agent.toAgent();

Returns the family and version number concatinated in a nice human readablestring.

varagent=useragent.parse(req.headers['user-agent']);agent.toAgent();// 'Chrome 15.0.874'

Agent.toString();

Returns the results of theAgent.toAgent() but also adds the parsed operatingsystem to the string in a human readable format.

varagent=useragent.parse(req.headers['user-agent']);agent.toString();// 'Chrome 15.0.874 / Mac OS X 10.8.1'// as it's a to string method you can also concat it with another string'your useragent is '+agent;// 'your useragent is Chrome 15.0.874 / Mac OS X 10.8.1'

Agent.toVersion();

Returns the version of the browser in a human readable string.

varagent=useragent.parse(req.headers['user-agent']);agent.toVersion();// '15.0.874'

Agent.toJSON();

Generates a JSON representation of the Agent. By using thetoJSON method weautomatically allow it to be stringified when supplying as to theJSON.stringify method.

varagent=useragent.parse(req.headers['user-agent']);agent.toJSON();// returns an objectJSON.stringify(agent);

OperatingSystem.toString();

Generates a stringified version of operating system;

varagent=useragent.parse(req.headers['user-agent']);agent.os.toString();// 'Mac OSX 10.8.1'

OperatingSystem.toVersion();

Generates a stringified version of operating system's version;

varagent=useragent.parse(req.headers['user-agent']);agent.os.toVersion();// '10.8.1'

OperatingSystem.toJSON();

Generates a JSON representation of the OperatingSystem. By using thetoJSONmethod we automatically allow it to be stringified when supplying as to theJSON.stringify method.

varagent=useragent.parse(req.headers['user-agent']);agent.os.toJSON();// returns an objectJSON.stringify(agent.os);

Device.toString();

Generates a stringified version of device;

varagent=useragent.parse(req.headers['user-agent']);agent.device.toString();// 'Asus A100'

Device.toVersion();

Generates a stringified version of device's version;

varagent=useragent.parse(req.headers['user-agent']);agent.device.toVersion();// '' , no version found but could also be '0.0.0'

Device.toJSON();

Generates a JSON representation of the Device. By using thetoJSON method weautomatically allow it to be stringified when supplying as to theJSON.stringify method.

varagent=useragent.parse(req.headers['user-agent']);agent.device.toJSON();// returns an objectJSON.stringify(agent.device);

Adding more features to the useragent

As I wanted to keep the core of the user agent parser as clean and fast aspossible I decided to move some of the initially planned features to a newplugin file.

These extensions to the Agent prototype can be loaded by requiring theuseragent/features file:

varuseragent=require('useragent');require('useragent/features');

The initial release introduces 1 new method, satisfies, which allows you to seeif the version number of the browser satisfies a certain range. It uses thesemver library to do all the range calculations but here is a small summary ofthe supported range styles:

  • >1.2.3 Greater than a specific version.
  • <1.2.3 Less than.
  • 1.2.3 - 2.3.4 :=>=1.2.3 <=2.3.4.
  • ~1.2.3 :=>=1.2.3 <1.3.0.
  • ~1.2 :=>=1.2.0 <2.0.0.
  • ~1 :=>=1.0.0 <2.0.0.
  • 1.2.x :=>=1.2.0 <1.3.0.
  • 1.x :=>=1.0.0 <2.0.0.

As it requires thesemver module to function you need to install itseperately:

npm install semver --save

Agent.satisfies('range style here');

Check if the agent matches the supplied range.

varagent=useragent.parse(req.headers['user-agent']);agent.satisfies('15.x || >=19.5.0 || 25.0.0 - 17.2.3');// trueagent.satisfies('>16.12.0');// false

Migrations

For small changes between version please review thechangelog.

Upgrading from 1.10 to 2.0.0

  • useragent.fromAgent has been removed.
  • agent.toJSON now returns an Object, useJSON.stringify(agent) for the oldbehaviour.
  • agent.os is now anOperatingSystem instance with version numbers. If youstill a string only representation doagent.os.toString().
  • semver has been removed from the dependencies, so if you are using therequire('useragent/features') you need to add it to your own dependencies

Upgrading from 0.1.2 to 1.0.0

  • useragent.browser(ua) has been renamed touseragent.is(ua).
  • useragent.parser(ua, jsua) has been renamed touseragent.parse(ua, jsua).
  • result.pretty() has been renamed toresult.toAgent().
  • result.V1 has been renamed toresult.major.
  • result.V2 has been renamed toresult.minor.
  • result.V3 has been renamed toresult.patch.
  • result.prettyOS() has been removed.
  • result.match has been removed.

License

MIT

About

Useragent parser for Node.js, ported from browserscope.org

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp