firefox-addonchrome-extension-manifest-v3

declarativeNetRequest set condition to the extension


I am working on a extension that downloads for the user content. (WebToEpub) Some websites check the origin header and block the request if it is wrong. How can i set the condition in the rule so that it only works for requests that originate from the extension?

I have tried the following rule as SessionRule: (commit WebToEpub #1857)

let rule = 
[{
    "id": 1,
    "priority": 1,
    "action": {
        "type": "modifyHeaders",
        "requestHeaders": [{ "header": "origin", "operation": "remove" }]
    },
    "condition": { "urlFilter" : "example.com"}
}];

Now i want the rule only to apply to the extension and not to all requests for this site. In chrome i use chrome.tabs.getCurrent() to get the tabid and add it as condition like this

"condition": { "urlFilter" : "example.com", "tabIds": [(await chrome.tabs.getCurrent()).id]}

In firefox this doesn't work as they have a warning in the documentation tabs.getCurrent(): "If you call it from a background script or a popup, it will return undefined." As WebToEpub is a popup it doesn't work. The current "solution" is this for firefox:

static async getActiveTab() {
    return new Promise(function (resolve, reject) {
        chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
            if ((tabs != null) && (0 < tabs.length)) {
                resolve(tabs[0].id);
            } else {
                reject();
            };
        });
    });
}

The problem is that it can result in the wrong id.

Does anyone have a better solution to set the condition so that it only applies to to the extension?


Solution

  • Thanks to @woxxom who nudged me in the right direction. The solution is to use runtime.getURL() as "initiatorDomains".

    let url = chrome.runtime.getURL("").split("/").filter(a => a != "");
    let id = url[url.length - 1];
    let rule = 
    [{
        "id": 1,
        "priority": 1,
        "action": {
            "type": "modifyHeaders",
            "requestHeaders": [{ "header": "origin", "operation": "remove" }]
        },
        "condition": { "urlFilter" : "example.com", "initiatorDomains": [id]}
    }];
    
    

    This solution works in chrome and firefox.