Skip to content

Instantly share code, notes, and snippets.

@jeffposnick
Last active December 25, 2022 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffposnick/8b4cbb3ddff5c6ab8cbd to your computer and use it in GitHub Desktop.
Save jeffposnick/8b4cbb3ddff5c6ab8cbd to your computer and use it in GitHub Desktop.
<html>
<body>
<p><button onclick="fetch('a');">fetch a</button></p>
<p><a href="b">go to b</a></p>
<script>
navigator.serviceWorker.register('sw.js');
</script>
</body>
</html>
self.addEventListener('install', event => {
// Bypass the waiting lifecycle stage, just in case there's an older version of this SW registration.
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', event => {
// Take control of all pages under this SW's scope immediately, instead of waiting for reload/navigation.
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
// In a real app, you'd use a more sophisticated URL check.
if (event.request.url.match(/a|b$/)) {
event.respondWith(new Response('here is your onfetch response'));
}
});
@guest271314
Copy link

@jeffposnick Is there any way to set headers or otherwise programmatically convince the ServiceWorker that fetch event should be fired when there is technically no Client or WindowClient?

The context is an MV3 ServiceWorker.

Right now I am using an offscreen document https://github.com/guest271314/offscreen-webrtc for one approach and window.open() https://github.com/guest271314/sw-transfer-stream for another approach to transfer data to arbitrary Web pages.

Ideally there would be some means to establish an arbitrary Web page as a WindowClient so we can use client.postMessage() and onmessage where the Web page is not necessarily within the scope of the ServiceWorker - without the need to create an entire document just to transfer or stream data. An ideas?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment