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

邮差的信 提交于 2019-12-04 14:21:28

You cite the 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.

Well, that explains the situation pretty well. Your options are:

  1. Wait until WebExtensions achieve better support for webRequest.

EDIT (Dec 2018): This is indeed now possible. Citing 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. Cancel, and not redirect, the request if it's absolutely imperative that no connection is made at all.

  2. Redirect in onBeforeSendHeaders instead. Considering that you're only checking the URL and that is available in that event, it shouldn't make a difference except that the TCP connection may be already established before you redirect.

    Note that the same code wouldn't work in Chrome - it doesn't expect a redirect in this request.

    As mentioned by you, unlike Chrome, redirecting to the same URL would produce a loop (because at this point the request needs to be remade from scratch).

    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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!