向 iframe 添加新的 header

add new header to iframe

如何仅针对受信任的请求

为每个传出请求添加新的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).

因此,要修改 headers,您需要:

  1. 声明您要修改请求;在您做出反应之前,它必须阻止请求。您需要将 "blocking" 添加到 API 调用。

  2. 您需要特殊权限,"webRequestBlocking"才能进行此类操作。将其添加到清单。

  3. 您需要从回调中return修改headers。

    chrome.webRequest.onBeforeSendHeaders.addListener(
      function(details){
        var headers = details.requestHeaders;
        /* ..modify headers.. */
        return { requestHeaders : headers };
      },
      { urls: [ "*://*.example.com/*" ] },
      [ 'blocking', 'requestHeaders' ]
    );