this.onpush = (event) => {
console.log(event.data);
// From here we can write the data to IndexedDB, send it to any open
// windows, display a notification, etc.
};
navigator.serviceWorker.register("serviceworker.js");
// Use serviceWorker.ready to ensure that you can subscribe for push
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
const options = {
userVisibleOnly: true,
applicationServerKey,
};
serviceWorkerRegistration.pushManager.subscribe(options).then(
(pushSubscription) => {
console.log(pushSubscription.endpoint);
// The push subscription details needed by the application
// server are now available, and can be sent to it using,
// for example, the fetch() API.
},
(error) => {
// During development it often helps to log errors to the
// console. In a production environment it might make sense to
// also report information about errors back to the
// application server.
console.error(error);
},
);
});PushManager: subscribe() method / notebook
PushManager: subscribe() method
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
btn.addEventListener("click", () => {
serviceWorkerRegistration.pushManager
.subscribe(options)
.then((pushSubscription) => {
// handle subscription
});
});