问题
I would like to read and modify (add) HTTP headers in a Chrome extension. I am using the chrome.webRequest API for the same. But i am still not able to read it. Here's my code.
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({name:"dummyHeader",value:"1"});
return {requestHeaders: details.requestHeaders};
},
{urls: ["<all_urls>"]},
["requestHeaders"]
);
What am i missing?
回答1:
You need to add the "blocking"
flag to the ExtraInfoSpec list in order to pause the request. Without this flag, the return value of an onBeforeSendHeaders
event listener is ignored.
chrome.webRequest.onBeforeSendHeaders.addListener(
function(details) {
details.requestHeaders.push({name:"dummyHeader",value:"1"});
return {requestHeaders: details.requestHeaders};
},
{urls: ["<all_urls>"]},
["requestHeaders", "blocking"]
//^^^^^^^^
);
I suggest to read the documentation more carefully, in particular the Registering event listeners section.
回答2:
But, for all reading it later, it is not solution for XmlHttpRequest.
It is not obvious but asynchronous request can't be block. More about this issue you can read at issiue 132731 If you need to change request headers for XmlHttpRequest you must use declarativeWebRequest
An example of implementation you can find at Chrome Rest Client background page (declarativeRequest.setRules() function).
来源:https://stackoverflow.com/questions/12960902/reading-and-modifying-the-http-get-request-in-a-chrome-extension