Cheatography
https://cheatography.com
Setup
Clone repo |
|
Install webserver |
|
Select app folder from cloned repo in webserver |
Always update the service worker |
Open DevTools (Right Click > Inspect) -> Application -> Service Workers -> Update on Reload |
|
|
Register a Service Worker
navigator.serviceWorker.register('sw.js') .then(function(swReg) { console.log('Service Worker is registered', swReg); swRegistration = swReg; })
|
Subscribe the user
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
updateSubscriptionOnServer(subscription);
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
updateSubscriptionOnServer(subscription);
isSubscribed = true;
})
});
|
Get Application Server Keys
Generate public/private keys |
|
Insert them into your application |
|
|
Handle Permission Denied
if (Notification.permission === 'denied') {
pushButton.textContent = 'Push Messaging Blocked.';
pushButton.disabled = true;
updateSubscriptionOnServer(null);
return;
}
if (isSubscribed) {
pushButton.textContent = 'Disable Push Messaging';
} else {
pushButton.textContent = 'Enable Push Messaging';
}
pushButton.disabled = false;
|
Handle a Push Event
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log([Service Worker] Push had this data: "${event.data.text()}" );
const title = 'Push Codelab';
const options = {
body: 'Yay it works.',
icon: 'images/icon.png',
badge: 'images/badge.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
|
Notification click
self.addEventListener('notificationclick', function(event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://developers.google.com/web/')
);
});
|
Unsubscribe the user
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
unsubscribeUser();
} else {
subscribeUser();
}
});
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
return subscription.unsubscribe();
}
})
.then(function() {
updateSubscriptionOnServer(null);
console.log('User is unsubscribed.');
isSubscribed = false;
updateBtn();
});
|
|
Created By
Metadata
Comments
No comments yet. Add yours below!
Add a Comment
More Cheat Sheets by [deleted]