關於 Chrome User-Agent Reduction
前陣子在處理公司應 Chrome User-Agent Reduction Plan 政策,盤點可能受影響之程式碼,這裡也記錄一下 User-Agent Reduction 這件事:
先說結論:User-Agent Reduction 旨在減少 user-agent 字串多餘資訊(或多餘的次版號)單純拿 user-agent 字串判斷的程式碼頂多 match 不到而已,應不至於造成 JS 扔出錯誤
以 https://developer.chrome.com/docs/privacy-sandbox/user-agent/#why-do-we-need-reduced-ua-and-ua-ch 內容來看:
The reduced User-Agent includes the browser's brand and a significant version, where the request came from (desktop or mobile), and the platform. To access more data, User-Agent Client Hints allow you to request specific information about the user's device or conditions.
减少 User-Agent 他們認為不必要帶的資訊,並將某些資訊帶到 headers 上而已。
為什麼 Chrome 要減少 User-Agent?
參照 https://developer.chrome.com/docs/privacy-sandbox/user-agent/#why-do-we-need-reduced-ua-and-ua-ch 提到
The granularity and abundance of detail can lead to user identification.The default availability of this information can lead to covert tracking.
乍看是打著保護使用者隱私的名號,但 User-Agent 本來就會被工程師拿來判讀使用者電腦或瀏覽器資訊,其他瀏覽器也是如此,根本原因可能還是如下:https://www.ithome.com.tw/news/149433
回到前面的 Chrome Developers 開發者網頁,裡面也有提到
Further, the User-Agent string has grown longer and more complex, which led to error-prone string parsing.
以前 IE 或早期 Edge 瀏覽器時,每個版本都有差異,不僅要判讀「瀏覽器名稱」還要判斷「瀏覽器版本」,IE 每差一個版本就差很多,code 可能會出現那種拿 User-Agent 來判斷 isIE9、isIE10、isIE11 之類的邏輯,當然這種邏輯只是簡單抓取 User-Agent 瀏覽器版本字串來比對,所以邏輯可能就很土炮比對字串位置之類的。
拉回 Chrome,若某些網頁服務也有對 Chrome 做類似的事情,那可能進入 100 版以後,User-Agent 版號三位數可能導致字串判讀出錯。我認為 Chrome 剛好藉此機會,來對 User-Agent 做一些精簡,順便把一些不必要的資訊拿掉(或改帶在 headers 上)。
本機電腦測試方式
瀏覽器打開 chrome://flags/#reduce-user-agent
把 Reduce User-Agent request header 設為 enable 即可。
設定好後打開我們的服務檢測是否正常運作或程式邏輯、 API event 是否有送出正常參數即可。
User-Agent 修改前後對比
可以參考這篇 https://www.chromium.org/updates/ua-reduction/ 明確列出修改後格式
修改前
Desktop
Mozilla/5.0 (<platform>; <oscpu>) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/<majorVersion>.<minorVersion>; Safari/537.36
Mobile
Mozilla/5.0 (Linux; Android <androidVersion>; <deviceModel>)
AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/<majorVersion>.<minorVersion> <deviceCompat>
Safari/537.36
修改後
Desktop
Mozilla/5.0 (<unifiedPlatform>) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/<majorVersion>.0.0.0 Safari/537.36
Mobile
Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/<majorVersion>.0.0.0 <deviceCompat> Safari/537.36
可以看到「瀏覽器名稱」還留著,更動的是 Platform、Device 、Version之類的資訊
iOS 系統 Chrome User-Agent 不影響
按照此篇 https://blog.chromium.org/2021/05/update-on-user-agent-string-reduction.html
Note: We have no plans to change the User-Agent string on Android WebView or Chrome for iOS at this time, but will make public updates if and when that changes.
iOS 環境 Chrome 與 Android WebView 是不會受影響的。
isMobile 與 navigator.userAgentData API
Google 建議若只是要判斷 isMobile 可以從 navigator.userAgentData 去取
const isMobile = navigator.userAgentData.mobile;
問題是按照 Can I use https://caniuse.com/?search=userAgentData 支援度尚不高,所以 userAgentData 暫時不考慮。