I currently learning about service workers, and in particular subscribing a user to push notifications. I've worked through the Web Push Notifications Guide and Adding Push Notifications to a Web App Code Lab that Google publishes - but I'm seeing two different ways of asking for a user's permission.
The guide asks using the Notification
interface of the Notifications API like this and then calls subscribe()
based on the return value of .requestPermission()
:
function askPermission() {
return new Promise(function(resolve, reject) {
const permissionResult = Notification.requestPermission(function(result) {
resolve(result);
});
if (permissionResult) {
permissionResult.then(resolve, reject);
}
})
.then(function(permissionResult) {
if (permissionResult !== 'granted') {
throw new Error('We weren\'t granted permission.');
}
});
}
And the Code Lab asks by only calling .subscribe()
(which will bring up the notification prompt) directly on the service worker registration's PushManager
like this:
function subscribeUser() {
const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey);
swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed.');
updateSubscriptionOnServer(subscription);
isSubscribed = true;
updateBtn();
})
.catch(function(err) {
console.log('Failed to subscribe the user: ', err);
updateBtn();
});
}
I've looked through the mozilla docs for PushManager.subscribe()
and Notification.requestPermission()
but am struggling to identify the trade-offs of each of Google's flows and in particular whether or not the extra step of Notification.requestPermission(..)
is necessary.
It's worth noting that .subscribe()
is currently marked as an experimental feature where-as .requestPermission()
is not.