Code in typescript
window.addEventListener('message', (event) => {
event.source.postMessage("response",event.origin)
});
get Error at "event.origin"
TS2349: This expression is not callable.
Each member of the union type '((message: any, targetOrigin: string, transfer?: Transferable[]) => void) | { (message: any, transfer: Transferable[]): void; (message: any, options?: PostMessageOptions): void; } | { ...; }' has signatures, but none of those signatures are compatible with each other.
Thank in advance
CodePudding user response:
I can't see the specific error you've mentioned in that code in the playground, but I do see two errors, so:
event.source
can benull
, but your code assumes it isn'tnull
. You have to handle that, because you can't donull.postMessage(/*...*/)
.event.origin
is a string, butevent.source
on aMessageEvent
(when it's notnull
) isn't necessarily a window object, so you can't assume the second parameter onpostMessage
allows a string. Sadly,postMessage
on different objects has differing parameter lists. Window'spostMessage
accepts a string as the second argument, but (for instance)MessagePort
's doesn't.
I'm going to assume since you're trying to pass a string to it, you expect event.source
to be a window. If so, you can solve both problems with a since type guard:
window.addEventListener('message', (event) => {
if (event.source instanceof Window) {
event.source.postMessage("response", event.origin);
}
});
null
never passes an instanceof
check, so that handles both cases.