WebExtension onBeforeReuest 未触发获取请求 API

WebExtension onBeforeReuest is not trigger for request from fetch API

Web 扩展开发的新手,我正在尝试这个 example。但是,当我 运行 这个扩展时,它不会触发监听器。

这是清单文件。

{
  "description": "Altering HTTP responses",
  "manifest_version": 2,
  "name": "http-response-filter",
  "version": "1.0",
  "homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/http-response",
  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "http://localhost:8000/*"
  ],

  "background": {
    "scripts": ["browser-polyfill.min.js", "background.js"]
  },
  "browser_specific_settings": {
    "gecko": {
      "strict_min_version": "57.0a1"
    }
  }
}

和background.js

function listener(details) {
  console.log("event trigger"); // not reaching to here
  let filter = browser.webRequest.filterResponseData(details.requestId);
  let decoder = new TextDecoder("utf-8");
  let encoder = new TextEncoder();

  filter.ondata = (event) => {
    console.log(event.data);
    let str = decoder.decode(event.data, { stream: true });
    str = str.replace(/Example/g, "WebExtension Example");
    filter.write(encoder.encode(str));
    filter.disconnect();
  };

  return {};
}

console.log("Extension"); // this prints on the extension's console

browser.webRequest.onBeforeRequest.addListener(
  listener,
  {
    urls: ["http://localhost:8000/*"],
    types: ["xmlhttprequest", "main_frame"],
  },
  ["blocking"]
);

我发现我需要将 xmlhttprequest 添加到过滤器中,以便为使用 fetch API 或 XmlHttpRequest 发出的请求触发 onBeforeRequesthttps://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/ResourceType

我有一个示例 html 页 运行s 与实时服务器。这是我发送获取请求的代码片段。

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      fetch("http://localhost:8000/ping")
        .then((res) => res.text())
        .then((dat) => console.log(dat))
        .catch((err) => console.log(err));
    </script>
  </body>
</html>

非常感谢有关此问题的任何帮助

引用 MDN:

To intercept resources loaded by a page (such as images, scripts, or stylesheets), the extension must have the host permission for the resource as well as for the main page requesting the resource.

因此,你还需要在manifest.json中添加127.0.0.1,因为它与localhost不同,后者实际上可以指向不同的IP。

  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "*://localhost/",
    "*://127.0.0.1/"
  ]