Skip to content

Instantly share code, notes, and snippets.

@johnmellor
Last active September 12, 2016 11:52
Show Gist options
  • Save johnmellor/d792819c4faa24a190bb7ea0138fba3e to your computer and use it in GitHub Desktop.
Save johnmellor/d792819c4faa24a190bb7ea0138fba3e to your computer and use it in GitHub Desktop.
Minimal push notifications demo (sends via cURL)
<!doctype html>
<!-- View this at https://rawgit.com/johnmellor/d792819c4faa24a190bb7ea0138fba3e/raw/ -->
<meta name=viewport content="initial-scale=1">
<a href="https://gist.github.com/johnmellor/d792819c4faa24a190bb7ea0138fba3e">View code</a><br>
<a href="https://rawgit.com/johnmellor/460bdac0c5b30832df898e67b4b7cedf/raw/">XHR variant</a><br><br>
<code id="code">Loading...</code>
<script>
navigator.serviceWorker.register('sw.js');
navigator.serviceWorker.ready.then(swr => {
swr.pushManager.subscribe({
applicationServerKey: new TextEncoder().encode('653317226796'),
userVisibleOnly: true
}).then(pushSubscription => {
// This part uses the proprietary GCM protocol. TODO: Switch to webpush.
var slash = pushSubscription.endpoint.lastIndexOf('/');
var url = pushSubscription.endpoint.substr(0, slash);
var token = pushSubscription.endpoint.substr(slash + 1);
document.getElementById('code').innerText =
// JUST FOR DEMO PURPOSES - NEVER PUT YOUR REAL AUTHORIZATION KEY ON A
// PUBLIC WEBPAGE! KEEP IT SERVER-SIDE.
'curl --header "Authorization: key=AIzaSyBBh4ddPa96rQQNxqiq_qQj7sq1JdsNQUQ" ' +
'--header Content-Type:"application/json" ' +
url + ' ' +
'-d "{\\"registration_ids\\":[\\"' + token + '\\"]}"';
});
});
</script>
self.addEventListener('install', () => skipWaiting());
self.addEventListener('activate', () => clients.claim());
self.addEventListener('push', event => {
event.waitUntil(registration.showNotification("Title", { body: "Text" }));
});
self.addEventListener('notificationclick', event => {
event.notification.close();
event.waitUntil(clients.matchAll().then(cs => {
for (var client of cs) {
if (client.url == registration.scope)
return client.focus();
}
return clients.openWindow(registration.scope);
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment