Enables event listeners to send response back to the event dispatcher.
Inspired by the FetchEvent which is available to Service Workers only, the RespondableEvent allows event listeners to send a response back to the dispatching EventTarget.
This is useful in scenarios where custom elements need to communicate with the host asynchronously or infrequently. For persisted messaging, use RespondableEvent to set up Channel Messaging instead.
The code snippet below sends an "authenticate" event to the hosting page.
const event = new RespondableEvent(
'authenticate',
token => {
if (token) {
// Responded.
} else {
// No response.
}
},
{ bubbles: true } // Available to the whole page.
);
element.dispatchEvent(event);
// If `respondWith()` is not called, `checkResponse()`
// function will callback with `undefined`.
event.checkResponse();In the hosting page, the following code snippet responds with a token.
window.addEventListener('authenticate', event => {
if (event.target === myTrustedElement && event.request === myTrustedRequest) {
event.respondWith('Hello, World!');
event.stopPropagation();
}
});The callback function passed to the constructor will be called at most once. Same as FetchEvent, the respondWith() function will throw if it is being called for more than once.
To reduce code complexity, the checkResponse() function guarantees the callback function will be called exactly once. The API design is similar to the HTMLFormElement.checkValidity() function:
- If
respondWith()was called,checkResponse()will returntrue. - If
respondWith()was never called,checkResponse()will call thecallbackfunction withundefined, and returnfalse.- Subsequent calls to
checkResponse()will returntrue.
- Subsequent calls to
It is recommended to put checkResponse() immediately after dispatchEvent().
The callback function follows the pattern found in MutationObserver and other observers. It is designed to limit the number of audience who can look at the response.
RespondableEventextends fromEvent, whereFetchEventextends fromExtendableEventrequestproperty is optional inRespondableEventwhere it is required inFetchEventcheckResponse()function is new inRespondableEvent
Like us? Star us.
Want to make it better? File us an issue.
Don't like something you see? Submit a pull request.