Subscribing to web push

Hi, I'm working on a chrome extension that subscribes to web push notifications. In Chrome's example for this, they await the call to the function that eventually calls self.registration.pushManager.subscribe. If you remove this await, when starting the extension you get the following error:
Failed to subscribe, error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
Failed to subscribe, error: AbortError: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker
I suspect there's some kind of race condition involved here. In any case, I can't await the call to that function becuase typescript does not support top-level await. How can I resolve this issue?
Chrome for Developers
Use Web Push  |  Chrome Extensions  |  Chrome for Developers
Step by step guide on how to use Web Push with Chrome Extensions
1 Reply
Max
MaxOP•3w ago
I was able to resolve this by subscribing to the pushmanager in response to the activate event:
self.addEventListener('activate', (e) => {
console.log('subscribing')
e.waitUntil(subscribe());
})
self.addEventListener('activate', (e) => {
console.log('subscribing')
e.waitUntil(subscribe());
})
Note that I used self.addEventListener rather than this.addEventListener like many chrome extension sources recommend. this isn't available in plasmo, but pallas noted that self works. Also, using ExtendableEvent.waitUntil is critical: it blocks until the promise it's passed resolves, ensuring the subscription is created before the service worker exits. It would be helpful if some documentation about this sort of thing somewhere, both about responding to events (this vs self) in BSWs, and about how to handle async setup stuff like the pushmanager. I was barely able to piece together docs between chrome's spotty references on extensions and plasmo's sparse docs

Did you find this page helpful?