Created
November 7, 2018 05:17
-
-
Save leaysgur/29d53d1d66ef6b00210c5f8ad088636c to your computer and use it in GitHub Desktop.
Use MessageChannel with ServiceWorker
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="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>ServiceWorker Messaging Test</title> | |
</head> | |
<body> | |
<script src="./main.js"></script> | |
</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
(async function main() { | |
await navigator.serviceWorker.register('./sw.js'); | |
const { $incBtn, $decBtn, $span } = initView(); | |
const ctrl = navigator.serviceWorker.controller; | |
const { port1, port2 } = new MessageChannel(); | |
// handle messages from service worker | |
// addEventListener() does not work...? | |
port1.onmessage = ev => { | |
$span.textContent = ev.data; | |
}; | |
// init service worker with `MessagePort` | |
ctrl.postMessage( | |
{ type: 'init' }, | |
[ port2 ] | |
); | |
// now, we can interact with service worker! | |
$incBtn.onclick = () => ctrl.postMessage({ type: '++' }); | |
$decBtn.onclick = () => ctrl.postMessage({ type: '--' }); | |
}()); | |
function initView() { | |
const $span = document.createElement('span'); | |
$span.textContent = '-'; | |
document.body.append($span); | |
const $incBtn = document.createElement('button'); | |
$incBtn.textContent = '++'; | |
document.body.append($incBtn); | |
const $decBtn = document.createElement('button'); | |
$decBtn.textContent = '--'; | |
document.body.append($decBtn); | |
return { $incBtn, $decBtn, $span }; | |
} |
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
let port; | |
let count = 0; | |
self.addEventListener('message', ev => { | |
const { type } = ev.data; | |
switch (type) { | |
case 'init': | |
port = ev.ports[0]; | |
break; | |
case '++': | |
count++; | |
break; | |
case '--': | |
count--; | |
break; | |
default: | |
} | |
port && port.postMessage(count); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment