UNPKG

12.5 kBMarkdownView Raw
1# UAParser.js
2
3<img align="right" src="https://raw.githubusercontent.com/faisalman/ua-parser-js/gh-pages/images/logo.png"> A JavaScript-based User-Agent string parser. Can be used either in browser (client-side) or in node.js (server-side) environment. Also available as jQuery/Zepto plugin, Bower/Meteor package, & RequireJS/AMD module. This library aims to identify detailed type of web browser, layout engine, operating system, cpu architecture, and device type/model, entirely from user-agent string with a relatively small footprint (~17KB when minified / ~6KB gzipped). Written in vanilla JavaScript, which means it doesn't require any other library and can be used independently. However, it's not recommended to use this library as browser detection since the result may not be more accurate than using feature detection.
4
5[![Build Status](https://travis-ci.org/faisalman/ua-parser-js.svg?branch=master)](https://travis-ci.org/faisalman/ua-parser-js)
6[![NPM downloads](https://img.shields.io/npm/dw/ua-parser-js.svg)](https://www.npmjs.com/package/ua-parser-js)
7[![NPM](https://img.shields.io/npm/v/ua-parser-js.svg)](https://www.npmjs.com/package/ua-parser-js)
8[![Bower](https://img.shields.io/bower/v/ua-parser-js.svg)](https://bower.io/)
9[![CDNJS](https://img.shields.io/cdnjs/v/UAParser.js.svg)](https://cdnjs.com/libraries/UAParser.js)
10
11* Author : Faisal Salman <<f@faisalman.com>>
12* Demo : http://faisalman.github.io/ua-parser-js
13* Source : https://github.com/faisalman/ua-parser-js
14
15# Constructor
16
17* `new UAParser([uastring][,extensions])`
18 * returns new instance
19
20* `UAParser([uastring][,extensions])`
21 * returns result object `{ ua: '', browser: {}, cpu: {}, device: {}, engine: {}, os: {} }`
22
23# Methods
24
25* `getBrowser()`
26 * returns `{ name: '', version: '' }`
27
28```sh
29# Possible 'browser.name':
302345Explorer, 360 Browser, Amaya, Android Browser, Arora, Avant, Avast, AVG,
31BIDUBrowser, Baidu, Basilisk, Blazer, Bolt, Brave, Bowser, Camino, Chimera,
32Chrome Headless, Chrome WebView, Chrome, Chromium, Comodo Dragon, Dillo,
33Dolphin, Doris, Edge, Epiphany, Facebook, Falkon, Fennec, Firebird, Firefox,
34Flock, GSA, GoBrowser, ICE Browser, IE, IEMobile, IceApe, IceCat, IceDragon,
35Iceape, Iceweasel, Iridium, Iron, Jasmine, K-Meleon, Kindle, Konqueror,
36LBBROWSER Line, Links, Lunascape, Lynx, MIUI Browser, Maemo Browser, Maemo,
37Maxthon, MetaSr Midori, Minimo, Mobile Safari, Mosaic, Mozilla, NetFront,
38NetSurf, Netfront, Netscape, NokiaBrowser, Oculus Browser, OmniWeb,
39Opera Coast, Opera Mini, Opera Mobi, Opera Tablet, Opera, PaleMoon, PhantomJS,
40Phoenix, Polaris, Puffin, QQ, QQBrowser, QQBrowserLite, Quark, QupZilla,
41RockMelt, Safari, Sailfish Browser, Samsung Browser, SeaMonkey, Silk, Skyfire,
42Sleipnir, Slim, SlimBrowser, Swiftfox, Tizen Browser, UCBrowser, Vivaldi,
43Waterfox, WeChat, Yandex, baidu, iCab, w3m, Whale Browser...
44
45# 'browser.version' determined dynamically
46```
47
48* `getDevice()`
49 * returns `{ model: '', type: '', vendor: '' }`
50
51```sh
52# Possible 'device.type':
53console, mobile, tablet, smarttv, wearable, embedded
54
55# Possible 'device.vendor':
56Acer, Alcatel, Amazon, Apple, Archos, Asus, BenQ, BlackBerry, Dell, Essential,
57GeeksPhone, Google, HP, HTC, Huawei, Jolla, Lenovo, LG, Meizu, Microsoft, Motorola,
58Nexian, Nintendo, Nokia, Nvidia, OnePlus, Ouya, Palm, Panasonic, Pebble, Polytron,
59RIM, Samsung, Sharp, Siemens, Sony[Ericsson], Sprint, Xbox, Xiaomi, ZTE, ...
60
61# 'device.model' determined dynamically
62```
63
64* `getEngine()`
65 * returns `{ name: '', version: '' }`
66
67```sh
68# Possible 'engine.name'
69Amaya, Blink, EdgeHTML, Gecko, Goanna, iCab, KHTML, Links, Lynx, NetFront,
70NetSurf, Presto, Tasman, Trident, w3m, WebKit
71
72# 'engine.version' determined dynamically
73```
74
75* `getOS()`
76 * returns `{ name: '', version: '' }`
77
78```sh
79# Possible 'os.name'
80AIX, Amiga OS, Android, Arch, Bada, BeOS, BlackBerry, CentOS, Chromium OS,
81Contiki, Fedora, Firefox OS, FreeBSD, Debian, DragonFly, Fuchsia, Gentoo, GNU,
82Haiku, Hurd, iOS, Joli, KaiOS, Linpus, Linux, Mac OS, Mageia, Mandriva, MeeGo,
83Minix, Mint, Morph OS, NetBSD, Nintendo, OpenBSD, OpenVMS, OS/2, Palm, PC-BSD,
84PCLinuxOS, Plan9, PlayStation, QNX, RedHat, RIM Tablet OS, RISC OS, Sailfish,
85Series40, Slackware, Solaris, SUSE, Symbian, Tizen, Ubuntu, Unix, VectorLinux,
86WebOS, Windows [Phone/Mobile], Zenwalk, ...
87
88# 'os.version' determined dynamically
89```
90
91* `getCPU()`
92 * returns `{ architecture: '' }`
93
94```sh
95# Possible 'cpu.architecture'
9668k, amd64, arm[64], avr, ia[32/64], irix[64], mips[64], pa-risc, ppc, sparc[64]
97```
98
99* `getResult()`
100 * returns `{ ua: '', browser: {}, cpu: {}, device: {}, engine: {}, os: {} }`
101
102* `getUA()`
103 * returns UA string of current instance
104
105* `setUA(uastring)`
106 * set UA string to parse
107 * returns current instance
108
109
110# Example
111
112```html
113<!doctype html>
114<html>
115<head>
116<script src="ua-parser.min.js"></script>
117<script>
118
119 var parser = new UAParser();
120
121 // by default it takes ua string from current browser's window.navigator.userAgent
122 console.log(parser.getResult());
123 /*
124 /// this will print an object structured like this:
125 {
126 ua: "",
127 browser: {
128 name: "",
129 version: ""
130 },
131 engine: {
132 name: "",
133 version: ""
134 },
135 os: {
136 name: "",
137 version: ""
138 },
139 device: {
140 model: "",
141 type: "",
142 vendor: ""
143 },
144 cpu: {
145 architecture: ""
146 }
147 }
148 */
149
150 // let's test a custom user-agent string as an example
151 var uastring = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Ubuntu/11.10 Chromium/15.0.874.106 Chrome/15.0.874.106 Safari/535.2";
152 parser.setUA(uastring);
153
154 var result = parser.getResult();
155 // this will also produce the same result (without instantiation):
156 // var result = UAParser(uastring);
157
158 console.log(result.browser); // {name: "Chromium", version: "15.0.874.106"}
159 console.log(result.device); // {model: undefined, type: undefined, vendor: undefined}
160 console.log(result.os); // {name: "Ubuntu", version: "11.10"}
161 console.log(result.os.version); // "11.10"
162 console.log(result.engine.name); // "WebKit"
163 console.log(result.cpu.architecture); // "amd64"
164
165 // do some other tests
166 var uastring2 = "Mozilla/5.0 (compatible; Konqueror/4.1; OpenBSD) KHTML/4.1.4 (like Gecko)";
167 console.log(parser.setUA(uastring2).getBrowser().name); // "Konqueror"
168 console.log(parser.getOS()); // {name: "OpenBSD", version: undefined}
169 console.log(parser.getEngine()); // {name: "KHTML", version: "4.1.4"}
170
171 var uastring3 = 'Mozilla/5.0 (PlayBook; U; RIM Tablet OS 1.0.0; en-US) AppleWebKit/534.11 (KHTML, like Gecko) Version/7.1.0.7 Safari/534.11';
172 console.log(parser.setUA(uastring3).getDevice().model); // "PlayBook"
173 console.log(parser.getOS()) // {name: "RIM Tablet OS", version: "1.0.0"}
174 console.log(parser.getBrowser().name); // "Safari"
175
176</script>
177</head>
178<body>
179</body>
180</html>
181```
182
183## Using node.js
184
185```sh
186$ npm install ua-parser-js
187```
188
189```js
190var http = require('http');
191var parser = require('ua-parser-js');
192
193http.createServer(function (req, res) {
194 // get user-agent header
195 var ua = parser(req.headers['user-agent']);
196 // write the result as response
197 res.end(JSON.stringify(ua, null, ' '));
198})
199.listen(1337, '127.0.0.1');
200
201console.log('Server running at http://127.0.0.1:1337/');
202```
203
204## Using requirejs
205
206```js
207requirejs.config({
208 baseUrl : 'js/lib', // path to your script directory
209 paths : {
210 'ua-parser-js' : 'ua-parser.min'
211 }
212});
213
214requirejs(['ua-parser-js'], function(UAParser) {
215 var parser = new UAParser();
216 console.log(parser.getResult());
217});
218```
219
220## Using CDN
221
222```html
223<script src="https://cdn.jsdelivr.net/npm/ua-parser-js@0/dist/ua-parser.min.js"></script>
224```
225
226## Using bower
227
228```sh
229$ bower install ua-parser-js
230```
231
232## Using meteor
233
234```sh
235$ meteor add faisalman:ua-parser-js
236```
237
238## Using TypeScript
239
240```sh
241$ npm install --save @types/ua-parser-js
242# Download TS type definition from DefinitelyTyped repository:
243# https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ua-parser-js
244```
245
246## Using jQuery/Zepto ($.ua)
247
248Although written in vanilla js (which means it doesn't depends on jQuery), this library will automatically detect if jQuery/Zepto is present and create `$.ua` object based on browser's user-agent (although in case you need, `window.UAParser` constructor is still present). To get/set user-agent you can use: `$.ua.get()` / `$.ua.set(uastring)`.
249
250```js
251// In browser with default user-agent: 'Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; Sprint APA7373KT Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0':
252
253// Do some tests
254console.log($.ua.device); // {vendor: "HTC", model: "Evo Shift 4G", type: "mobile"}
255console.log($.ua.os); // {name: "Android", version: "2.3.4"}
256console.log($.ua.os.name); // "Android"
257console.log($.ua.get()); // "Mozilla/5.0 (Linux; U; Android 2.3.4; en-us; Sprint APA7373KT Build/GRJ22) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0"
258
259// reset to custom user-agent
260$.ua.set('Mozilla/5.0 (Linux; U; Android 3.0.1; en-us; Xoom Build/HWI69) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13');
261
262// Test again
263console.log($.ua.browser.name); // "Safari"
264console.log($.ua.engine.name); // "Webkit"
265console.log($.ua.device); // {vendor: "Motorola", model: "Xoom", type: "tablet"}
266console.log(parseInt($.ua.browser.version.split('.')[0], 10)); // 4
267
268// Add class to <body> tag
269// <body class="ua-browser-safari ua-devicetype-tablet">
270$('body').addClass('ua-browser-' + $.ua.browser.name + ' ua-devicetype-' + $.ua.device.type);
271```
272
273## Extending regex patterns
274
275* `UAParser([uastring,] extensions)`
276
277Pass your own regexes to extend the limited matching rules.
278
279```js
280// Example:
281var myOwnRegex = [[/(myownbrowser)\/([\w\.]+)/i], [UAParser.BROWSER.NAME, UAParser.BROWSER.VERSION]];
282var myParser = new UAParser({ browser: myOwnRegex });
283var uaString = 'Mozilla/5.0 MyOwnBrowser/1.3';
284console.log(myParser.setUA(uaString).getBrowser()); // {name: "MyOwnBrowser", version: "1.3"}
285```
286
287
288# Development
289
290## Contribute
291
292* Fork and clone this repository
293* Make some changes as required
294* Write a unit test to showcase your feature
295* Run the test suites to make sure the changes you made didn't break anything `$ npm run test`
296* Commit and push to your own repository
297* Submit a pull request to this repository under `develop` branch
298* Profit? $$$
299
300## Build
301
302Build a minified & packed script
303
304```sh
305$ npm run build
306```
307
308
309# Donate
310
311Do you use & like UAParser.js but you don’t find a way to show some love? If yes, please consider donating to support this project. Otherwise, no worries, regardless of whether there is support or not, I will keep maintaining this project. Still, if you buy me a cup of coffee I would be more than happy though :)
312
313[![Support via PayPal](https://cdn.rawgit.com/twolfson/paypal-github-button/1.0.0/dist/button.svg)](https://www.paypal.me/faisalman/)
314
315
316# License
317
318MIT License
319
320Copyright (c) 2012-2021 Faisal Salman <<f@faisalman.com>>
321
322Permission is hereby granted, free of charge, to any person obtaining a copy
323of this software and associated documentation files (the "Software"), to deal
324in the Software without restriction, including without limitation the rights
325to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
326copies of the Software, and to permit persons to whom the Software is
327furnished to do so, subject to the following conditions:
328
329The above copyright notice and this permission notice shall be included in all
330copies or substantial portions of the Software.
331
332THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
333IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
334FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
335AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
336LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
337OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
338SOFTWARE.