Firefox Addon 中的 OnBeforeRequest URL 重定向(从 Chrome 扩展转换)

2024-01-13

我想将我的 Chrome 扩展程序转换为 Firefox。到目前为止一切顺利,除了我有一个网址重定向webRequest.onBeforeRequest在 Chrome 扩展程序中,这是Firefox WebExtensions 中不允许 https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities#webRequest.

现在我不确定如何在 Firefox 中实现这一点。
在 Chrome 中background.js它看起来像这样:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    console.log('onBeforeRequest');

    var returnuri;
    returnuri = details.url;
    if ((details.url.indexOf("/malicious/") > -1) || (details.url.indexOf("/bad/") > -1)){
      //I want to redirect to safe content
      returnuri = details.url + (/\&tag=/.test(details.url) ? "" : '/safe/');
    }else{
      returnuri = details.url;
    }
    return {redirectUrl: returnuri};
  },
  {
    urls: [
      "*://malicious.com/*"
    ],
    types: ["main_frame"]
  },
  ["blocking"]
);

你引用了Web 扩展文档 https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Chrome_incompatibilities#webRequest:

请求可以是:

  • 仅在以下时间取消onBeforeRequest
  • 仅在以下位置修改/重定向onBeforeSendHeaders

...

不允许重定向onBeforeRequest or onHeadersReceived,但允许在onBeforeSendHeaders.

嗯,这很好地解释了情况。您的选择是:

  1. 等到 WebExtensions 获得更好的支持webRequest.

编辑(2018 年 12 月): 现在确实可以了。引用文档 https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest#Modifying_requests:

对于其中一些事件,您可以修改请求。具体来说,您可以:

  • cancel the request in:
    • onBeforeRequest
    • onBeforeSendHeaders
    • onAuthRequired
  • redirect the request in:
    • onBeforeRequest
    • onHeadersReceived

[...]

  1. 如果绝对不能建立任何连接,则取消而不是重定向请求。

  2. 重定向至onBeforeSendHeaders反而。考虑到您只是检查 URL 并且该 URL 在该事件中可用,因此除了在重定向之前可能已经建立 TCP 连接之外,它应该没有什么区别。

    请注意,相同的代码在 Chrome 中不起作用 - 它不希望在此请求中进行重定向。

    正如您所提到的,与 Chrome 不同,重定向到相同的 URL 会产生循环(因为此时需要从头开始重新发出请求)。

    In general, if you need to inspect something available in an earlier event and act on it later, you can flag the request in onBeforeRequest by saving its requestId and later redirecting the same request ID in onBeforeSendHeaders. Unfortunately, the docs state that requestId is not supported either.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Firefox Addon 中的 OnBeforeRequest URL 重定向(从 Chrome 扩展转换) 的相关文章

随机推荐