-
Notifications
You must be signed in to change notification settings - Fork 851
Description
To accompany the new workbox-window
library in v4, and standardize the functionality that's needed for the skipWaiting
message handler proposed in #1753 as well as what's already implemented in
workbox/packages/workbox-broadcast-cache-update/BroadcastCacheUpdate.mjs
Lines 185 to 207 in 208850c
_initWindowReadyDeferreds() { | |
// A mapping between navigation events and their deferreds. | |
this._navigationEventsDeferreds = new Map(); | |
// The message listener needs to be added in the initial run of the | |
// service worker, but since we don't actually need to be listening for | |
// messages until the cache updates, we only invoke the callback if set. | |
self.addEventListener('message', (event) => { | |
if (event.data.type === 'WINDOW_READY' && | |
event.data.meta === 'workbox-window' && | |
this._navigationEventsDeferreds.size > 0) { | |
if (process.env.NODE_ENV !== 'production') { | |
logger.debug(`Received WINDOW_READY event: `, event); | |
} | |
// Resolve any pending deferreds. | |
for (const deferred of this._navigationEventsDeferreds.values()) { | |
deferred.resolve(); | |
} | |
this._navigationEventsDeferreds.clear(); | |
} | |
}); | |
} | |
} |
I'm proposing a new set of methods on workbox.core
:
-
registerMessageCallback({messageType, callback})
will take care of adding in amessage
event handler (if one doesn't already exist) that will in turn check for incomingmessage
s whoseevent.data.type === messageType
, and when found, runawait callback(event)
for each registered event. The callback mechanism will be wrapped inevent.waitUntil()
(for browsers that support it: MessageEvent within the SW global should have waitUntil() w3c/ServiceWorker#669 (comment)) -
unregisterMessageCallback({messageType, callback})
will do the opposite, and either unregister a specificcallback
, or ifcallback
isnull
, unregister all callbacks for the givenmessageType
.
I think that keeping track of messageType
values can be done on a per-module basis, i.e. the constant used by workbox-broadcast-cache-update
can be defined locally there.
One additional area for discussion is whether this proposal can end up powering the mechanism that's already in place in workbox.core
for registering callbacks that can be run when there's a global QUOTA_EXCEEDED
error. There's a lot of similarities, but invoking callbacks triggered by an exception is different from invoking callbacks triggered by a message
event.