0

Web 扩展开发新手,我正在尝试这个示例。但是,当我运行此扩展程序时,它不会触发侦听器。

这是清单文件。

{
  "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到过滤器中才能触发onBeforeRequest使用 fetch API 或 XmlHttpRequest 发出的请求。https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/ResourceType

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

<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>

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

4

1 回答 1

1

引用MDN

要拦截页面加载的资源(例如图像、脚本或样式表),扩展必须具有资源的主机权限以及请求资源的主页。

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

  "permissions": [
    "webRequest",
    "webRequestBlocking",
    "*://localhost/",
    "*://127.0.0.1/"
  ]
于 2021-03-01T08:49:03.293 回答