巩鹏军的博客

HOME

User-Agent

18 Aug 2022

关于User-Agent(简称UA),最近做了一些调研,总结一些常识。

UA的定义

RFC9110 Section-3.5 定义了user agent,特别说明不止浏览器,爬虫、命令行程序都是user agent。

RFC9110 Section-10.1.5 定义了 User-Agent HTTP请求头字段的格式和内容。

HTTP是无状态协议,user agent发送的每个HTTP请求时都要携带User-Agent字段。

UA的用途

UA解析

一句话总结:UA解析不难但是很难保证100%可靠。

Using the user agent to detect the browser looks simple, but doing it well is, in fact, a very hard problem. 使用UA检测浏览器看起来很简单,但是做得很好,实际上是一个非常困难的问题。

As there is no uniformity of the different part of the user agent string, this is the tricky part. 由于用户代理字串的不同部分缺乏统一性,这是一个较难对付的问题。

A technological survey must be in place to adapt the script when new browser versions are coming out. 当新的浏览器版本发布的时候,必须进行一次技术调研,看是否需要和怎么修改UA解析脚本以适应新的浏览器。

Mobile device detection

推荐方法:优先使用功能侦测(Feature Detect),最后没办法时才fallback到UA检测。

Use Navigator.maxTouchPoints to detect if the user’s device has a touchscreen. Then, default back to checking the user agent screen only if (!(“maxTouchPoints” in navigator)) { /Code here/}. Mobile device detection

UA解析开源库 ua-parser

ua-parser开源库集合支持各种常见编程语言,其中uap-core项目中的正则表达式文件regexes.yaml是关键,可以参考使用。

正则表达式工具网站在解析时很有用:https://regex101.com/

UA演进

Google正在推动废除UA或冻结UA字段(只读),用UA Client Hints方案替代,并已形成W3C草案。

参考资料

关于我

专注于IM即时通讯全技术栈的程序员,关注获取更多IM技术文章。

gongpengjunblog

IM小蓝天

微信扫描二维码,关注我的公众号