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.
A Promise
that resolves to a PushSubscription
object.
this.onpush = (event) => {
console.log(event.data);
};
navigator.serviceWorker.register("serviceworker.js");
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
const options = {
userVisibleOnly: true,
applicationServerKey,
};
serviceWorkerRegistration.pushManager.subscribe(options).then(
(pushSubscription) => {
console.log(pushSubscription.endpoint);
},
(error) => {
console.error(error);
},
);
});
subscribe()
calls should be done in response to a user gesture, such as clicking a button, for example:
btn.addEventListener("click", () => {
serviceWorkerRegistration.pushManager
.subscribe(options)
.then((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.