javascript - 向 iframe 添加新 header

标签 javascript php iframe google-chrome-extension

如何为每个传出请求添加新 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 ,您需要:

  1. 声明您要修改请求;必须阻止该请求,直到您使用react。您需要将“blocking”添加到API调用中。

  2. 您需要特殊权限“webRequestBlocking”才能执行此类操作。将其添加到 list 中。

  3. 您需要从回调中返回修改后的 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/

相关文章:

php - 如何编写迁移以撤消 Laravel 中的唯一约束?

javascript - 如何在 iframe 中选择一个 div?

javascript - <div> 内容未在 &lt;iframe&gt; 中加载

javascript - jQuery 获取 IFRAME 内容并将其设置为 div

php - 使用PHP将SND/AU转换为mp3

javascript - PHP 中的用户时区问题修复

javascript - 为什么 var x = x = x || {} 比 var x = x || 更彻底{}?

javascript - 无法在 Android 设备上运行 React-Native 示例代码

javascript - 在 json_encode 输出中获取最后 2 个数据

php - js和css按需加载