Reading and modifying the HTTP GET request in a Chrome extension

余生颓废 提交于 2019-12-22 14:45:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!