Created
January 13, 2022 04:43
-
-
Save guest271314/5a283e786ccad44103f0bc52ea1721f1 to your computer and use it in GitHub Desktop.
Persistent ServiceWorker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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