Skip to content

Instantly share code, notes, and snippets.

@arikanmstf
Last active December 14, 2020 10:54
Show Gist options
  • Save arikanmstf/89952ed61736d683bb113fd2b267e324 to your computer and use it in GitHub Desktop.
Save arikanmstf/89952ed61736d683bb113fd2b267e324 to your computer and use it in GitHub Desktop.
Service Worker Communication
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no"/>
<meta name="google" content="notranslate"/>
<meta name="msapplication-tap-highlight" content="no"/>
<meta http-equiv="cache-control" content="no-store"/>
<meta http-equiv="expires" content="0"/>
<script>
// register service worker:
if (navigator.serviceWorker) {
navigator.serviceWorker.register('/service-worker.js').then(function() {
return navigator.serviceWorker.ready;
})
.then(function(registration) {
console.log(registration); // service worker is ready and working...
});
navigator.serviceWorker.addEventListener('message', function(event) {
console.log(event.data.message); // Hello World !
});
}
</script>
<title>Service Worker Communication</title>
</head>
<body>
<div id="root" class="root"></div>
</body>
</html>
function messageToClient(client, data) {
return new Promise(function(resolve, reject) {
const channel = new MessageChannel();
channel.port1.onmessage = function(event){
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
client.postMessage(JSON.stringify(data), [channel.port2]);
});
}
self.addEventListener('push', function (event) {
if (event && event.data) {
self.pushData = event.data.json();
if (self.pushData) {
event.waitUntil(self.registration.showNotification(self.pushData.title, {
body: self.pushData.body,
icon: self.pushData.data ? self.pushData.data.icon : null
}).then(function() {
clients.matchAll({type: 'window'}).then(function (clientList) {
if (clientList.length > 0) {
messageToClient(clientList[0], {
message: self.pushData.body // suppose it is: "Hello World !"
});
}
});
}));
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment