Last active
September 1, 2019 05:07
-
-
Save moshfeu/e93104cc3429b7b2eeff0a9aa05cae21 to your computer and use it in GitHub Desktop.
Show notification from the service worker
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
<button onclick="sendMessage('start')">Start Listen</button> | |
<button onclick="sendMessage('stop')">Stop Listen</button> | |
<button onclick="sendMessage('notification')">Send a Notification</button> | |
<script> | |
let se; | |
navigator.serviceWorker.register('/sw.js').then(data => { | |
se = data.active; | |
console.log('se ready!'); | |
}); | |
function sendMessage(message) { | |
if (!se) { | |
console.log('sw is not ready yet'); | |
return; | |
} | |
se.postMessage(message); | |
} | |
Notification.requestPermission().then(registration => { | |
console.log(registration); | |
}); | |
</script> |
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
let interval; | |
self.addEventListener('notificationclick', function(event) { | |
console.log('On notification click: ', event.notification.tag); | |
event.notification.close(); | |
event.waitUntil(clients.matchAll({ | |
type: 'window' | |
}).then(function(clientList) { | |
if (clientList.length) { | |
const [client] = clientList; | |
if ('focus' in client) { | |
return client.focus(); | |
} else if (clients.openWindow) { | |
return clients.openWindow('/#notification'); | |
} | |
} | |
})); | |
}); | |
function startListen() { | |
interval = setInterval(() => { | |
console.log(Date.now()); | |
}, 1000); | |
} | |
function stopListen() { | |
clearInterval(interval); | |
} | |
function sendTestNotification() { | |
setTimeout(() => { | |
self.registration.showNotification(`I'm a notification from the service worker!!`, { | |
body: 'How cool is that?', | |
icon: '', | |
tag: '', | |
}); | |
}, 1000); | |
} | |
self.addEventListener('message', ({data}) => { | |
switch (data) { | |
case 'start': | |
startListen(); | |
break; | |
case 'stop': | |
stopListen(); | |
break; | |
case 'notification': | |
sendTestNotification(); | |
break; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment