Redirect a web accessible script with declarative net requests

78 views
Skip to first unread message

Jean Lomdes

unread,
Jun 11, 2024, 9:23:16 AMJun 11
to Chromium Extensions
Hi,
It seems impossible to redirect the extension own script to another with this rule.
I tried with "chrome-extension://" and without it.
Is it impossible to redirect chrome-extension:// ?

[
  {
    "id": 1,
    "action": {
      "type": "redirect",
      "redirect": {
        "url": "chrome-extension://${chrome.runtime.id}/scriptB.js"
      }
    },
    "condition": {
      "urlFilter": "chrome-extension://${chrome.runtime.id}/scriptA.js"
    }
  }
]

Thank you,
Jean
Message has been deleted

woxxom

unread,
Jun 11, 2024, 10:11:37 AMJun 11
to Chromium Extensions, woxxom, Jean Lomdes
Sorry, I didn't look at urlFilter. Indeed declarativeNetRequest shouldn't work for extension's own scripts because these are local files that don't go through the network process.

You can try self.onfetch handler in the background script:

self.onfetch = e => {
  if (e.request.url === "chrome-extension://${chrome.runtime.id}/scriptA.js") {
    e.respondWith(Response.redirect("chrome-extension://${chrome.runtime.id}/scriptB.js"));
  }
};

On Tuesday, June 11, 2024 at 5:08:11 PM UTC+3 woxxom wrote:
Assuming you know that this code should be used in an extension script such as the background script and web_accessible_resources properly declares scriptB.js, the problem is likely that you need to add resourceTypes: ['script'] to condition. There's also a bug with redirecting from pages without an origin such as a local file:// and probably sandboxed pages/frames.

Jean Lomdes

unread,
Jun 11, 2024, 11:07:40 AMJun 11
to Chromium Extensions, woxxom, Jean Lomdes

Content script adding scriptA.js (web accessible)  : 
var s = document.createElement('script');
s.src = chrome.runtime.getURL('scriptA.js');
document.body.appendChild(s);

Service worker: 
self.addEventListener("fetch", (event) => {
console.log(event);
});

I don't get event fetch fired.  
But I do get the event if I manually open the url to scriptA.js on a new tab  chrome-extension://............/scriptA.js
How come? 

woxxom

unread,
Jun 11, 2024, 11:11:09 AMJun 11
to Chromium Extensions, Jean Lomdes, woxxom
There's no workaround in this case because onfetch of the extension is called only when the request is made by an extension page, whereas for web_accessible_resources the request is made by the web page.
Reply all
Reply to author
Forward
0 new messages