Saying the phrase "user agent" or "user agent string" is tantamount to saying a swear word. Developers used to use the user agent to detect if a browser had a given feature, instead of, you know, checking to see if the feature actually existed via object or property detection. Those days are behind us though, but one of the web's dirty secrets is that the user agent still has many uses. One frequent use, for example, is detecting which mobile theme to offer up; this detection can be done on both the client and server sides. I recently found Tobie Langel's ua-parser, a great repo which provides simple UA parsing in JavaScript, PHP, and Python.
说短语“用户代理”或“用户代理字符串”无异于说脏话。 开发人员过去常常使用用户代理来检测浏览器是否具有给定功能,而不是通过对象或属性检测来检查该功能是否确实存在。 尽管那些日子已经过去了,但是网络上的肮脏秘密之一是用户代理仍然有很多用途。 例如,一种经常使用的方法是检测要提供的移动主题。 这种检测可以在客户端和服务器端进行。 我最近发现了Tobie Langel的ua-parser ,它是一个很棒的仓库,它可以用JavaScript,PHP和Python提供简单的UA解析。
样本用户代理 (Sample User Agent)
'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3'
'Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3'
JavaScript用法 (JavaScript Usage)
var uaParser = require('ua-parser'),
uaParser.parse(navigator.userAgent);
console.log(ua.tostring()); // -> "Safari 5.0.1"
console.log(ua.toVersionString()); // -> "5.0.1"
console.log(ua.family); // -> "Safari"
console.log(ua.major); // -> 5
console.log(ua.minor); // -> 0
console.log(ua.patch); // -> 1
PHP用法 (PHP Usage)
// Require the library
require("UAParser.php");
// Parse the UA
$result = UA::parse();
// Get loads of information! :)
print $result->full; // -> Chrome 16.0.912/Mac OS X 10.6.8
print $result->browserFull; // -> "Chrome 16.0.912"
print $result->browser; // -> "Chrome"
print $result->version; // -> "16.0.912"
print $result->major; // -> 16 (minor, build, & revision also available)
print $result->osFull; // -> "Mac OS X 10.6.8"
print $result->os; // -> "Mac OS X"
print $result->osVersion; // -> "10.6.8"
print $result->osMajor; // -> 10 (osMinor, osBuild, & osRevision also available)
Python用法 (Python Usage)
# Import the lib
from ua_parser import user_agent_parser
# Parse the user agent
user_agent_parser.Parse(request.META.get('HTTP_USER_AGENT'))
print result_dict['user_agent']
# {'major': '5', 'minor': '1', 'family': 'Mobile Safari', 'patch': None}
print result_dict['os']
# {'major': '5', 'patch_minor': None, 'minor': '1', 'family': 'iOS', 'patch': None}
print result_dict['device']
# {'is_spider': False, 'is_mobile': True, 'family': 'iPhone'}
The code samples above are all easily recognizable by those who can use them; using user agent information is simple, and the API is as well. Well done to Tobie for this nice library.
上面的代码示例都可以被使用它们的人员轻松识别。 使用用户代理信息很简单,API也是如此。 对于这个很好的库,Tobie做得很好。