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

OnBeforeRequest URL redirect in Firefox Addon (Conversion from Chrome Extension)

我想将我的 Chrome 扩展程序转换为 Firefox。到目前为止一切顺利,除了我在 Chrome 扩展中的 webRequest.onBeforeRequest 中有一个 url 重定向,即 not allowed in Firefox WebExtensions

现在我不确定如何在 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"]
);

您引用 WebExtensions docs:

Requests can be:

  • canceled only in onBeforeRequest
  • modified/redirected only in onBeforeSendHeaders

...

Redirection is not allowed in onBeforeRequest or onHeadersReceived, but is allowed in onBeforeSendHeaders.

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

  1. 等待 WebExtensions 更好地支持 webRequest

编辑(2018 年 12 月):现在确实有可能。引用 the documentation:

On some of these events, you can modify the request. Specifically, you can:

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

[...]

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

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

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

    如您所述,与Chrome不同,重定向到相同的URL会产生循环(因为此时需要重新请求)。

    一般来说,如果您需要检查早期事件中可用的内容并在以后对其进行操作,您可以通过保存其 requestId 来标记 onBeforeRequest 中的请求,并且稍后在 onBeforeSendHeaders. 中重定向相同的请求 ID 不幸的是,文档声明 requestId 也不被支持。