chrome extension插件替换网络请求中的useragent

发布于:2024-05-06 ⋅ 阅读:(41) ⋅ 点赞:(0)

感觉Chrome商店中的插件不能很好的实现自己想要的效果,那么就来自己动手吧。
本文以百度为例:

一般来说网页请求如下:

请添加图片描述

当前使用的useragent是User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36
s

需要把这个给换点,查了很久的Chrome的文档,看到有个相关的说明,找了个比较靠谱的,经过很多的尝试终于试验成功了。

本例子使用的 mainfest v3,查了很多的文档说的是使用的 webRequestBlocking 这个权限跟API,但是开头就有如下的问题描述。

Note: As of Manifest V3, the “webRequestBlocking” permission is no longer available for most extensions. Consider “declarativeNetRequest”, which enables use the declarativeNetRequest API. Aside from “webRequestBlocking”, the webRequest API is unchanged and available for normal use. Policy installed extensions can continue to use “webRequestBlocking”.

依照文档,之前老的 block 被弃用了,需要使用新的 declarativeNetRequest 方式, 文档地址https://developer.chrome.com/docs/extensions/reference/api/declarativeNetRequest

其中的规则包含很多种:

  1. “block” Block the network request.
  2. “redirect” Redirect the network request.
  3. “allow” Allow the network request. The request won’t be intercepted if there is an allow rule which matches it.
  4. “upgradeScheme” Upgrade the network request url’s scheme to https if the request is http or ftp.
  5. “modifyHeaders” Modify request/response headers from the network request.
  6. “allowAllRequests”
    Allow all requests within a frame hierarchy, including the frame request itself.

感觉这个 modifyHeaders 还挺靠谱的。然后看到如下有一个看起来可以用的例子,

{
   
  "id"