Methods
onPostMessage(target, origin, messageType, handler)
Register an event handler for a post message on a valid target, like a window or an iframe.
The handler will only be executed, if the messageType as well as the origin match. The messageType must be
part of the payload, using the key "type", which emitPostMessage
does automatically.
Putting the origin as an obligatory parameter at the second place, is deliberate by design, to force everyone to really think about, what to use here. Usually, most people, just throw in the "*" wildcard, paying no attention to the security implications. Please really think about what to use here.
A word of advice: keep in mind, that, contrary to most other events in javascript, post messages actually work asynchronously (so you cannot be sure, that the handler has been executed, directly after a post message has been sent) and that messages/payload are not transferred as-is, but are cloned, using the "structured clone algorithm", which means, that not every javascript object is transferable without losses.
Parameters:
Name | Type | Description |
---|---|---|
target |
Window | HTMLIFrameElement | window/iframe to register the handler to (iframes are automatically resolved to the contentWindow) |
origin |
String | the origin the received post message has to have, for the handler to get executed (defaults to "*", if receiving a nullish value) |
messageType |
String | the type/name the post message has to have, for the handler to get executed (will be checked using the key "type" in the message's payload) |
handler |
function | the handler to execute, if a post message, matching all conditions, is received |
- Source:
- See:
Throws:
error if target is not usable
Returns:
Example
const removeAgainFunction = onPostMessage(window, '*', 'foobar-message', () => { doSomething(); });
onPostMessage(iframeElement, 'https://foobar.com:80/', 'foobar-message', e => { resizeIframe(e.data.payload.height); });