Skip to content

Proposal: workbox-messages module #1848

@jeffposnick

Description

@jeffposnick

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

_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 a message event handler (if one doesn't already exist) that will in turn check for incoming messages whose event.data.type === messageType, and when found, run await callback(event) for each registered event. The callback mechanism will be wrapped in event.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 specific callback, or if callback is null, unregister all callbacks for the given messageType.

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DiscussAn open question, where input from the community would be appreciated.New Project IdeaIdeas for a new, standalone module.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions