Created
September 30, 2021 09:11
-
-
Save flancer64/70786de9ba401a03a398bb90f58ddbd2 to your computer and use it in GitHub Desktop.
Medium post about communication between app and service workers (https://medium.com/p/3c719f6f646e/edit)
This file contains hidden or 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 lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>SW Messages</title> | |
<link rel="manifest" href="./pwa.webmanifest"> | |
<script> | |
const queue = {}; | |
const generateMsgId = () => `${(new Date()).getTime()}`; | |
navigator.serviceWorker.register('sw.js'); | |
navigator.serviceWorker.addEventListener('message', (event) => { | |
const msg = event.data; | |
if (typeof queue[msg.id] === 'function') | |
queue[msg.id](msg.payload); | |
}); | |
function sendMsgToSw(payload) { | |
const id = generateMsgId(); | |
return new Promise((resolve) => { | |
queue[id] = resolve; | |
const msg = {id, payload}; | |
self.navigator.serviceWorker | |
.ready | |
.then((reg) => reg.active.postMessage(msg)); | |
}); | |
} | |
sendMsgToSw('message from app') | |
.then((res) => console.log(JSON.stringify(res))); | |
</script> | |
</head> | |
<body></body> | |
</html> |
This file contains hidden or 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
{ | |
"background_color": "#D9D9FF", | |
"description": "SW Messages", | |
"display": "standalone", | |
"icons": [ | |
{ | |
"src": "./img/favicon-192.png", | |
"sizes": "192x192", | |
"type": "image/png" | |
}, { | |
"src": "./img/favicon-512.png", | |
"sizes": "512x512", | |
"type": "image/png" | |
} | |
], | |
"name": "SW Messages", | |
"scope": "./", | |
"short_name": "SW Messages", | |
"start_url": "./", | |
"theme_color": "#D9D9FF" | |
} |
This file contains hidden or 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
/** | |
* @param {MessageEvent} event | |
*/ | |
function onMessage(event) { | |
const msg = event.data; | |
const id = msg.id; | |
const res = `answer from SW to msg #${id}.`; | |
event.source.postMessage({id, payload: res}); | |
} | |
self.addEventListener('message', onMessage); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment