navigator.serviceWorker.ready is not ready

Highlighted
Shopify Partner
5 0 0

 Hello,

 

I'm trying to use service worker in my Shopify store
service worker is register proper but navigator.serviceWorker.ready always remain pending

Here is my code:

if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('https://www.mystore.com/apps/cnv/sw.js',{scope:'/apps/cnv/'}).then(function(registration) {
console.log('Service worker registration succeeded:', registration)
console.log('ready ', navigator.serviceWorker.ready);
});
}

Output:

ServiceWorkerRegistration {scope: "https://www.mystore.com/apps/cnv/", active: ServiceWorker, installing: null, navigationPreload: NavigationPreloadManager, sync: SyncManager, …}
    active: ServiceWorker {scriptURL: "https://www.mystore.com/apps/cnv/sw.js", state: "activated", onerror: null, onstatechange: null}
    installing: null
    navigationPreload: NavigationPreloadManager {}
    onupdatefound: null
    paymentManager: PaymentManager {instruments: PaymentInstruments, userHint: ""}
    pushManager: PushManager {}
    scope: "https://www.mystore.com/apps/cnv/"
    sync: SyncManager {}
    updateViaCache: "imports"
    waiting: null
    __proto__: ServiceWorkerRegistration


I'm using a proxy for retrieve sw.js and it is working fine also service worker register successfully

 

my problem is when I'm trying to access the navigator.serviceWorker.ready it always returns pending something like that

Promise {<pending>} 
__proto__: Promise [[PromiseStatus]]:"pending" [[PromiseValue]]: undefined

I want to resolve that promises
I tried but I didn't know how to resolved promises.

Can anyone know regarding this issue?

0 Likes
Tourist
11 1 1

A promise will always return "pending" until you resolve it. A promise can be resolved by calling `.then()` or by using `async / await` which is a very new JS introduction.

MDN has a link that explains how to resolve `navigator.serviceWorker.ready` by calling `.then()`.
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/ready

 

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.ready
  .then(function(registration) {
    console.log('A service worker is active:', registration.active);

    // At this point, you can call methods that require an active
    // service worker, like registration.pushManager.subscribe()
  });
} else {
  console.log('Service workers are not supported.');
}

 

0 Likes