Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Persistent ServiceWorker
<!DOCTYPE html>
<html>
<head>
<title>Persistent ServiceWorker</title>
<style>
body *:not(script) {
display: block;
white-space: pre;
}
</style>
</head>
<body>
<p>Persistent ServiceWorker</p>
<data></data>
<script type="module" src="./script.js"></script>
</body>
</html>
navigator.serviceWorker.addEventListener('controllerchange', (e) => {
console.log(e.type);
es = new EventSource('./?persistentServiceWorker');
es.addEventListener('persistentServiceWorker', (e) => {
const { lastEventId } = e;
document.querySelector('data').textContent = JSON.stringify(
{ lastEventId, ...JSON.parse(e.data) },
null,
2
);
});
es.addEventListener('open', (e) => {
// console.log(e.type);
});
es.addEventListener('error', (e) => {
// console.log(e);
});
});
const sw = await navigator.serviceWorker.register('sw.js', {
scope: './',
});
let es;
const start = new Date();
let id = 0;
self.addEventListener('install', (event) => {
console.log(event.type);
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', async (event) => {
console.log(event.type);
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', async (event) => {
if (event.request.url.includes('persistentServiceWorker')) {
const now = new Date();
const message =
`event: persistentServiceWorker\n` +
`retry: 15000\n` +
`id: ${id++}\n` +
`data:{"start":"${start}",` +
`"now": "${now}",` +
` "minutes":"${(now - start) / 60000}"}\n\n`;
const blob = new Blob([message], { type: 'text/event-stream' });
event.respondWith(
new Response(blob, {
headers: { 'Content-Type': 'text/event-stream' },
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment