Using chrome.declarativeNetRequest to update the First Document (HTML) Fetch request call

176 views Asked by At

We have an array of tab ids stored in chrome storage, using those I wanted to modify the user-agent of the First Document Fetch call on a webPage of those tabs.

i am using chrome.declarativeNetRequest API to dynamically update the rules with new Tab Ids whenever there is an update on any tab (chrome.tabs.onUpdated). But the first call always seems to bypass the eventListener because tabs.onUpdated are triggered after the first fetch call has been made. All the other requests after that are updated as intented. How can I modify the First request.

We previously in MV2 architecture used to do the same using chrome.webRequest.onBeforeSendHeaders event directly, but in Mv3 blocking request is not allowed.

background.js :

chrome.tabs.onUpdated.addListener(function (request, sender, callback) {
    chrome.storage.local.get(["tabs"], (tabs) => {
        const ruleId = 1;
        const rules = {
            removeRuleIds: [ruleId],
            addRules: [{
                id: ruleId,
                priority: 1,
                condition: {
                    tabIds: tabs,
                    resourceTypes: ["main_frame", "sub_frame", "xmlhttprequest"],
                },
                action: {
                    type: "modifyHeaders",
                    requestHeaders: [{
                        header: "user-agent",
                        operation: "set",
                        value: MY_USER_AGENT            
}],
                }
            }],
        };

        chrome.declarativeNetRequest.updateSessionRules(rules);
    });
});
0

There are 0 answers