有能力的可以看官方文档:https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#manifest
有一个需求,想通过插件的方式,修改请求头里面的user-agent,比如修改为iphone的头:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25
原本浏览器的请求头是:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36
通过查询发现,v2版本修改请求头的方式为:但是这种方式已经被废弃掉了,因为不安全
chrome.webRequest.onBeforeSendHeaders.addListener((details) => {
let reqHeaders = details.requestHeaders;
if (reqHeaders) {
reqHeaders.forEach((header) => {
if (header.name == "User-Agent") {
header.value = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25"
console.log(header.value) //Extension does change the value but it is never applied
}
});
}
return { requestHeaders: reqHeaders }; //This should apply the new value but doesn't
}, { urls: ["<all_urls>"] }, ["requestHeaders"]);
所以v3版本使用了声明式网络请求的方式declarativeNetRequest:
1.首先要在Manifest文件中添加一下权限:
"permissions": [
"storage",
"cookies",
"tabs",
"declarativeNetRequest",
"declarativeNetRequestWithHostAccess",
"declarativeNetRequestFeedback"
],
"declarative_net_request": {
"rule_resources": [{
"id": "1",
"enabled": false,
"path": "rules_1.json"
}]
},
2.需要配置一个规则文件rules_1.json:
配置规则说明:https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#rules
[
{
"id": 12,
"priority": 1,
"action": {
"type": "modifyHeaders",
"requestHeaders": [
{
"header": "user-agent",
"operation": "set",
"value": "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25"
}
]
},
"condition": {
"urlFilter": "|https*",
"resourceTypes": [
"csp_report",
"font",
"image",
"main_frame",
"media",
"object",
"other",
"ping",
"script",
"stylesheet",
"sub_frame",
"webbundle",
"websocket",
"webtransport",
"xmlhttprequest"
]
}
}
]
然后重新加载一下拓展:
然后点击一下,再重新刷一下网页,打开检查,看一下网络请求里面的user-agent是否发生了改变:
可以看到,请求头里面的user-agent已经改变了,并且网页内容已经变成了移动端样式
看一下没有修改之前的页面结构和user-agent:
想要关闭这个修改,只需要将"enabled"改为false即可,然后重新加载拓展,并且点击一下拓展,然后重新刷新网页就可以了文章来源:https://www.toymoban.com/news/detail-429213.html
但是这种方式就是需要修改manifest文件,非常的不灵活,想要通过点击按钮切换的话,需要用到另外一个api:updateDynamicRules,下一篇文章会讲如何通过点击按钮就可以切换,非常的方便! 文章来源地址https://www.toymoban.com/news/detail-429213.html
到了这里,关于chrome extensions插件declarativeNetRequest修改user-agent方法manifest v3版的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!