Last active
October 2, 2018 15:00
-
-
Save felipebernardes/5ee5ebe545f780e9d0af77d9ecb168f9 to your computer and use it in GitHub Desktop.
Example/POC of messaging between main js thread and SW thread. 1) download and unzip 2) run 'make start' in your terminal 3) access localhost:1234 in your browser
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title></title> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
if('serviceWorker' in navigator){ | |
navigator.serviceWorker.register('/service-worker.js').then(function(reg){ | |
console.log("SW registration succeeded. Scope is "+reg.scope); | |
function sendMessageToSW(msg){ | |
navigator.serviceWorker.controller.postMessage(msg); | |
} | |
sendMessageToSW(JSON.stringify(window.performance)); | |
}).catch(function(err){ | |
console.error("SW registration failed with error "+err); | |
}); | |
} | |
</script> | |
</body> | |
</html> |
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
start: | |
php -S localhost:1234 |
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
console.log("SW Startup!"); | |
self.addEventListener('install', function(event) { | |
event.waitUntil(self.skipWaiting()); // Activate worker immediately (no need to refresh page) | |
}); | |
self.addEventListener('activate', function(event) { | |
event.waitUntil(self.clients.claim()); // Become available to all pages (no need to refresh page) | |
}); | |
self.addEventListener('message', function(event){ | |
console.log(JSON.parse(event.data)); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment