'How to inject service-worker.js to a webpage via Chrome Extension? I want to add offline functionality to the existing page
Goal: I want to add offline functionality to the online webpage via Chrome Browser Extension.
TLDR:
- [✔️] CSS injection
- [✔️] custom JS injection
- [✔️] JS assets from the webpage internally redirected via declarativeNetRequest
- [❌] injected service-worker.js on "the website" so Chrome can "install offline PWA"
Additional info
Current state: Changing any CSS or JS is no problem. It's done with content scripts (https://developer.chrome.com/docs/extensions/mv3/content_scripts/). And for additional JavaScript functionality, I'm injecting additional script injected.js through injector.js.
The code for injector.js looks like this:
const s = document.createElement("script");
s.src = chrome.runtime.getURL("script-dist.js");
(document.head || document.documentElement).appendChild(s);
s.onload = function () {
s.parentNode.removeChild(s);
};
Scripts already on the online website are checked "on load" through chrome.declarativeNetRequest (https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/) and swapped to prepared file copy through Internal Redirect (Code 307) that I've downloaded from the website and included to the files in the browser extension.
The problem: But here's the catch. I can't figure out how to inject "a whole" file. Because the Progressive Web Apps (PWA) application needs to have a js file as service-worker.js, I haven't figured out how to "inject it" into the current website. All I'm getting are Cross-Origin Resource Sharing (CORS) errors.
Here's a PWA Offline Fallback template I want to inject into the existing page: https://glitch.com/edit/#!/offline-fallback-demo?path=service-worker.js%3A1%3A0, where the most important is the service-worker.js and offline.html
How would you solve this issue?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
