如何为每个传出请求添加新 header (仅适用于受信任的请求)
chrome.webRequest.onBeforeSendHeaders.addListener(function(details){
var headers = details.requestHeaders;
console.log("=========BEFORE==========");
console.log(headers);
headers.push({
name: "CSRF",
value: "CSRFTOKEN"
});
console.log("=========AFTER==========");
console.log(headers);
},
{urls: [ "*://*.example.com/*" ]},['requestHeaders']);
甚至还可以将此 header 添加到 iframe
var attr ={"src":"http://example.com/test.php"};
var s = zen.utils.createElement(document,"iframe",attr);
document.body.appendChild(s);
这是打印所有 header 的示例 test.php 文件
<?php
$header=array_merge(getallheaders(),apache_response_headers());
print_r($header);
最佳答案
阅读the documentation 。强调我的:
If the optional
opt_extraInfoSpec
array contains the string'blocking'
(only allowed for specific events), the callback function is handled synchronously. That means that the request is blocked until the callback function returns.In this case, the callback can return a
webRequest.BlockingResponse
that determines the further life cycle of the request. Depending on the context, this response allows cancelling or redirecting a request (onBeforeRequest
), cancelling a request or modifying headers (onBeforeSendHeaders
,onHeadersReceived
), or providing authentication credentials (onAuthRequired
).
因此,要修改 header ,您需要:
声明您要修改请求;必须阻止该请求,直到您使用react。您需要将
“blocking”
添加到API调用中。您需要特殊权限
“webRequestBlocking”
才能执行此类操作。将其添加到 list 中。您需要从回调中返回修改后的 header 。
chrome.webRequest.onBeforeSendHeaders.addListener( function(details){ var headers = details.requestHeaders; /* ..modify headers.. */ return { requestHeaders : headers }; }, { urls: [ "*://*.example.com/*" ] }, [ 'blocking', 'requestHeaders' ] );
关于javascript - 向 iframe 添加新 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28558217/