UAParser.js用户代理检测 JavaScript 库
UAParser.js 是一个 JavaScript 库,用于从用户代理数据中检测浏览器、引擎、操作系统、CPU 和设备类型/模型。占用空间相对较小(~17KB minified,~6KB gzipped),可在浏览器(客户端)或 node.js(服务器端)使用。
Using HTML
<!doctype html> <html> <head> <script src="ua-parser.min.js"></script> <script> var parser = new UAParser(); console.log(parser.getResult()); /* /// This will print an object structured like this: { ua: "", browser: { name: "", version: "", major: "" //@deprecated }, engine: { name: "", version: "" }, os: { name: "", version: "" }, device: { model: "", type: "", vendor: "" }, cpu: { architecture: "" } } */ // Default result depends on current window.navigator.userAgent value // Now let's try a custom user-agent string as an example var uastring1 = "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"; parser.setUA(uastring1); var result = parser.getResult(); // You can also use UAParser constructor directly without having to create an instance: // var result = UAParser(uastring1); console.log(result.browser); // {name: "Chromium", version: "15.0.874.106"} console.log(result.device); // {model: undefined, type: undefined, vendor: undefined} console.log(result.os); // {name: "Ubuntu", version: "11.10"} console.log(result.os.version); // "11.10" console.log(result.engine.name); // "WebKit" console.log(result.cpu.architecture); // "amd64" // Do some other tests var uastring2 = "Mozilla/5.0 (compatible; Konqueror/4.1; OpenBSD) KHTML/4.1.4 (like Gecko)"; console.log(parser.setUA(uastring2).getBrowser().name); // "Konqueror" console.log(parser.getOS()); // {name: "OpenBSD", version: undefined} console.log(parser.getEngine()); // {name: "KHTML", version: "4.1.4"} 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'; console.log(parser.setUA(uastring3).getDevice().model); // "PlayBook" console.log(parser.getOS()) // {name: "RIM Tablet OS", version: "1.0.0"} console.log(parser.getBrowser().name); // "Safari" </script> </head> <body> </body> </html>
Using node.js
$ npm install ua-parser-js
var http = require('http'); var parser = require('ua-parser-js'); http.createServer(function (req, res) { // get user-agent header var ua = parser(req.headers['user-agent']); // write the result as response res.end(JSON.stringify(ua, null, ' ')); }) .listen(1337, '127.0.0.1'); console.log('Server running at http://127.0.0.1:1337/');
Using TypeScript
$ npm install --save @types/ua-parser-js # Download TS type definition from DefinitelyTyped repository: # https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/ua-parser-js
评论