Simple Service Worker Example
https://github.com/matthew-andrews/serviceworker-simple
HTML
<div style="max-width: 700px; margin: 0 auto 0 auto;">
<button id="swinstall">Install Service Worker</button>
<button id="swuninstall">Uninstall Service Worker</button>
<button id="desktopNotify">Show Desktop notification</button>
<div id="js-log" style="height: 400px; overflow: scroll; color: white; background: black; font-family: monospace; line-height: 150%; font-size: 12px; padding: 7px;"></div> <a href="http://mattandre.ws">mattandre.ws</a> <a href="http://twitter.com/andrewsmatt">@andrewsmatt</a>
</div>
JavaScript
// https://jsfiddle.net/zalun/d80qawf9/
window.addEventListener('message', function () {
debugger;
});
function log() {
var el = document.createElement('div');
el.innerHTML = Array.prototype.join.call(arguments, '<br />');
document.getElementById('js-log').appendChild(el);
}
function notifyMe() {
// Let's check if the browser supports notifications
if (!("Notification" in window)) {
return alert("This browser does not support desktop notification");
}
var msg = "Hi there, this is a desktop notification!";
// Let's check whether notification permissions have already been granted
if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification(msg);
} else if (Notification.permission !== "denied") {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
var notification = new Notification(msg);
}
});
}
}
var register = null;
if (navigator.serviceWorker) {
navigator.serviceWorker.addEventListener('message', function(event) {
log('<SW>' + event.data);
});
log("Browser supports Service Worker");
if (navigator.serviceWorker.current) {
log("Current Service Worker state: \\o/");
log('Go to chrome://serviceworker-internals/ or about:serviceworkers to see Service Worker debug output');
} else {
log("No Service Worker active...");
}
document.getElementById('swinstall').addEventListener('click', function () {
log('About to try to install a Service Worker');
navigator.serviceWorker.register('/arcturus/7aekd2hc/3/show_js/', {
scope: '/arcturus/7aekd2hc/3/show_js/'
})
.then(function (serviceWorker) {
register = serviceWorker;
log('Successfully installed ServiceWorker');
log('Go to...