I have a vue js pwa project,and i want to have access to the service-worker registration object in different components.In my main component,App.vue i register the service-worker like so:
created(){
if ("serviceWorker" in navigator && "PushManager" in window) {
console.log("Service Worker and Push is supported");
navigator.serviceWorker
.register("/service-worker.js")
.then(function(swReg) {
console.log("Service Worker is registered");
console.log(swReg)
})
.catch(function(error) {
console.error("Service Worker Error", error);
});
} else {
console.warn("Push messaging is not supported");
}
}
the registration is performed successfully , then in a child component i get the register object like this:
created(){
navigator.serviceWorker.getRegistrations().then(registrations => {
registrations.pushManager.getSubscription()
.then(function(subscription) {
this.isSubscribed = !(subscription === null);
if (this.isSubscribed) {
console.log('User IS subscribed.');
} else {
console.log('User is NOT subscribed.');
}
});
console.log(registrations);
});
but that only returns an error:
Uncaught (in promise) TypeError: Cannot read property 'getSubscription' of undefined
the weird part is the console log i have at the end of the created method logs a normal register service worker and is not "undefined". how should i properly get the register obj?