This is a draft cheat sheet. It is a work in progress and is not finished yet.
Install and verify webserver
unsubscribe
you need to call unsubscribe() on a PushSubscription.
Back in your scripts/main.js file, change the pushButton click listener in initializeUI() to the following
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
unsubscribeUser();
} else {
subscribeUser();
}
});
|
|
|
Handle Push event
You need to listen for this event and show a notification as a result.
Add the following code to your sw.js file:
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));
});
self.addEventListener('push', ... );
const title = 'Push Codelab';
const options = {
body: 'Yay it works.',
icon: 'images/icon.png',
badge: 'images/badge.png'
};
self.registration.showNotification(title, options);
|
|
|
Subscribe to User
Add this code to the main.js
function initializeUI() {
pushButton.addEventListener('click', function() {
pushButton.disabled = true;
if (isSubscribed) {
// TODO: Unsubscribe user
} else {
subscribeUser();
}
});
// Set the initial subscription value
swRegistration.pushManager.getSubscription()
.then(function(subscription) {
isSubscribed = !(subscription === null);
updateSubscriptionOnServer(subscription);
if (isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
}
updateBtn();
});
}
|
|