The subscribe()
method of the PushManager
interface subscribes to a push service.
It returns a Promise
that resolves to a PushSubscription
object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription.
PushManager.subscribe(options).then(function(pushSubscription) { } );
A Promise
that resolves to a PushSubscription
object.
this.onpush = function(event) {
console.log(event.data);
}
navigator.serviceWorker.register('serviceworker.js');
navigator.serviceWorker.ready.then(
function(serviceWorkerRegistration) {
var options = {
userVisibleOnly: true,
applicationServerKey: applicationServerKey
};
serviceWorkerRegistration.pushManager.subscribe(options).then(
function(pushSubscription) {
console.log(pushSubscription.endpoint);
}, function(error) {
console.log(error);
}
);
});
subscribe()
calls should be done in response to a user gesture, such as clicking a button, for example:
btn.addEventListener('click', function() {
serviceWorkerRegistration.pushManager.subscribe(options)
.then(function(pushSubscription) {
});
})
This is not only best practice — you should not be spamming users with notifications they didn't agree to — but going forward browsers will explicitly disallow notifications not triggered in response to a user gesture. Firefox is already doing this from version 72, for example.