错误:参数 4 的值无效.属性“方法”:意外属性

Error: Invalid value for argument 4. Property 'method': Unexpected property

本文关键字:属性 方法 意外 参数 错误 无效      更新时间:2023-09-26

我正在尝试更改用户发出的请求的请求方法(发出POST请求(,但出现此错误:

Error in event handler for webRequest.onBeforeSendHeaders/1: Error: Invalid value for argument 4. Property 'method': Unexpected property.

我的代码是这样的:

chrome.webRequest.onBeforeSendHeaders.addListener(function(data) {
    console.log(data);
    return {method: "POST"};
}, { 
    urls: ["<all_urls>"]
}, ["blocking", "requestHeaders"]);

我错过了什么吗?我搜索了很多,但我找不到任何可以更改请求方法的内容webRequest

通过扩展 API 不会立即支持更改 HTTP 方法。有几种方法可以获得所需的结果。在下面的答案中,我只会解释如何对 sub_framemain_frame 类型的请求执行此操作,因为这可能是您想要的(对于 imagestylesheet 等类型的 POST 实际上没有意义(。

您可以修改请求器,使其通过内容脚本启动 POST 请求而不是 GET 请求。 例如,通过定位<form>并将action设置为"POST"

一种通用的有效方法是拦截请求并重定向到您的扩展页面,该扩展页面又将表单提交到所需的目标。不要忘记将页面添加到 web_accessible_resources .可以通过 URL(查询字符串或引用片段(将参数传递给框架,或者将参数存储在后台页的字典中,并使用扩展消息传递 API 进行通信。
示例(使用查询字符串传递 URL(:

chrome.webRequest.onBeforeRequest.addListener(function(details) {
    var url = chrome.runtime.getURL('redirector.html') +
            '?' + encodeURIComponent(details.url)
    return {
        redirectUrl: url
    };
}, { 
    types: ['main_frame', 'sub_frame'],
    urls: ['*://example.com/*']
}, ['blocking']);

redirector.html(将此页面添加到web_accessible_resources

<form method="POST" id="form"></form>
<script src="redirector.js"></script>

redirector.js可以包含(注意:参数的验证留给读者作为练习(:

var form = document.forms['form'];
// URL is passed via the parameters
// "chrome-extension://[extensionid]/redirector.html?http%3A%2F%2Fexample.com%2F
//                                                  ^
//                                                  becomes http://example.com
form.action = decodeURIComponent(location.search.slice(1));
// Example: Append extra form data
var input = document.createElement('input');
input.type = 'text'; // Default
input.value = 'extra data';
form.appendChild(input);
form.submit();

这是一个非常简单的例子。如果要将更多数据传递到页面,请选择适当的参数序列化(例如 JSON 或 &param=value (。有关(动态生成的(表单的详细信息,请阅读文档:<form>HTMLFormElement