Skip to content

Instantly share code, notes, and snippets.

@moshfeu
Last active September 1, 2019 05:07
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 moshfeu/e93104cc3429b7b2eeff0a9aa05cae21 to your computer and use it in GitHub Desktop.
Save moshfeu/e93104cc3429b7b2eeff0a9aa05cae21 to your computer and use it in GitHub Desktop.
Show notification from the service worker
<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>
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