Compare commits

...

2 commits

Author SHA1 Message Date
b2347b0466 Add support for postMessage
All checks were successful
ci/woodpecker/push/build Pipeline was successful
2023-07-24 01:47:46 +02:00
e4829976e4 Broadcast channel 2023-07-24 01:46:50 +02:00
2 changed files with 28 additions and 9 deletions

View file

@ -4,21 +4,28 @@
import { onMount } from 'svelte'; import { onMount } from 'svelte';
let node; let node;
onMount(() => { onMount(() => {
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
addEventListener('load', function () { addEventListener('load', function () {
navigator.serviceWorker.register('/service-worker.js'); navigator.serviceWorker.register('/service-worker.js');
}); });
const channel = new BroadcastChannel('sw-messages'); if (BroadcastChannel) {
channel.addEventListener('message', (event) => { const channel = new BroadcastChannel('sw-messages');
new Toast({ target: node }); channel.addEventListener('message', (event) => {
}); console.log(event.data);
new Toast({ target: node });
});
} else {
navigator.serviceWorker.addEventListener('message', (evt) => {
console.log(evt.data);
new Toast({ target: node });
});
}
navigator.serviceWorker.ready.then((registration) => { navigator.serviceWorker.ready.then((registration) => {
console.log(registration); registration.active.postMessage('Save client');
console.log('registered service worker');
}); });
} }
}); });

View file

@ -14,6 +14,12 @@ const ASSETS = [
...prerendered // dynamic routes ...prerendered // dynamic routes
]; ];
let client;
addEventListener('message', event => {
client = event.source;
});
self.addEventListener('install', (event) => { self.addEventListener('install', (event) => {
// Create a new cache and add all files to it // Create a new cache and add all files to it
async function addFilesToCache() { async function addFilesToCache() {
@ -24,7 +30,7 @@ self.addEventListener('install', (event) => {
event.waitUntil(addFilesToCache()); event.waitUntil(addFilesToCache());
}); });
const channel = new BroadcastChannel('sw-messages');
self.addEventListener('activate', (event) => { self.addEventListener('activate', (event) => {
@ -36,7 +42,13 @@ self.addEventListener('activate', (event) => {
} }
event.waitUntil(deleteOldCaches()); event.waitUntil(deleteOldCaches());
channel.postMessage({title: 'Cache downloaded!'}); let channel;
if(BroadcastChannel) {
channel = new BroadcastChannel('sw-messages');
channel.postMessage({title: 'Cache Downloaded'});
} else {
client.postMessage("Cache Downloaded")
}
}); });
self.addEventListener('fetch', (event) => { self.addEventListener('fetch', (event) => {