WebExtension: Block request after response header received in Firefox and Chrome Extension

Well. Firefox finally admitted that Chrome’s extension system is better than it’s XUL or Add-on SDK.

So from Firefox 45+, it started to support WebExtension. And now, it even does not allow any extension that is not built with WebExtension API.

This is a good news, because if you want your extension run on both Chrome and Firefox. you won’t need to build twice.

However, even Firefox is trying to support all of the WebExtension API. There are still some differences between Chrome and Firefox.

Recently I got this one.

I was trying to block some requests with the WebRequest API after response header just received. In Chrome, you can easily do it with an onHeadersReceived listener. like this:

 chrome.webRequest.onHeadersReceived.addListener(
    function (details) {
        let block = THE CONDITIONS THAT YOU WANT TO USE;
        return {cancel: block};

    },
    {urls: ["URL PATTERN"], types: ["TYPES"]},
    ["blocking"]); 

But in Firefox, this is not gonna work. Because in Firefox, you can not block a request after the response headers received, you can only redirect it. So you need to to this:

 chrome.webRequest.onHeadersReceived.addListener(
    function (details) {
        let block = THE CONDITIONS THAT YOU WANT TO USE;
        return {cancel: block, redirectUrl: "://127.0.0.1"};

    },
    {urls: ["URL PATTERN"], types: ["TYPES"]},
    ["blocking"]); 

with the redirectUrl: “://127.0.0.1”, you will redirect it to a local address, and means block it.

Leave a Reply

Your email address will not be published. Required fields are marked *