Skip to content

Instantly share code, notes, and snippets.

@nobita4176
Created August 18, 2016 02:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nobita4176/18c3281d607116791d11c91c190dc511 to your computer and use it in GitHub Desktop.
Save nobita4176/18c3281d607116791d11c91c190dc511 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Web Push API example</title>
<style>pre {white-space: pre-wrap;}</style>
</head>
<body>
<main>
<h1>Push</h1>
<button>begin to subscribe</button>
<pre id="endpoint"></pre>
<pre id="key_p256"></pre>
<pre id="key_auth"></pre>
`<pre id="command"></pre>`
</main>
<script async>
(function() {
var btn = document.querySelector('button');
var arraybuffer_to_base64 = function(ab) {
return btoa(
String.fromCharCode.apply(null, new Uint8Array(ab))
).replace(/\+/g, '-').replace(/\//g, '_');
};
btn.addEventListener('click', function() {
if (! ('serviceWorker' in window.navigator)) {return;}
window.navigator.serviceWorker.register('/worker.js')
.then(function(registration) {
window.console.log(':-) : ' + registration.scope);
registration.pushManager.subscribe()
.then(function(subscription) {
document.querySelector('#endpoint').textContent = subscription.endpoint;
document.querySelector('#key_p256').textContent = arraybuffer_to_base64(subscription.getKey('p256dh'));
document.querySelector('#key_auth').textContent = arraybuffer_to_base64(subscription.getKey('auth'));
});
})
.catch(function(error) {
window.console.error(':-( : ' + error);
});
});
})();
</script>
</body>
</html>
self.addEventListener('push', function(ev) {
ev.waitUntil(
self.registration.showNotification('!', {
'body': '@',
'tag': 'notification',
'icon': '/assets/img/logo.png'
})
);
});
self.addEventListener('notificationclick', function(ev) {
ev.notification.close();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment