【问题标题】:WebExtension onBeforeReuest is not trigger for request from fetch APIWebExtension onBeforeReuest 不会触发来自 fetch API 的请求
【发布时间】:2021-05-30 16:53:57
【问题描述】:

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

我有一个使用 live-server 运行的示例 html 页面。这是我发送获取请求的代码 sn-p。

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

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

【问题讨论】:

  • 尝试在模式中省略端口:"http://localhost/*"
  • @wOxxOm 谢谢。我通过更新清单文件以及 background.js 文件进行了尝试。但仍然没有运气。另外,我尝试将 url 替换为 https://jsonplaceholder.typicode.com/todos/1 进行测试。但仍然无法正常工作:(
  • 然后你点击了 about:debugging 页面上的重新加载按钮?
  • 是的。甚至尝试删除并再次添加
  • 页面地址也是http://localhost?否则,您需要将其添加到权限中。

标签: javascript fetch firefox-addon-webextensions chrome-webrequest


【解决方案1】:

引用MDN:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-01-16
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多