Search code examples
stenciljs

window.parent.postMessage to @Listener


We have a requirement that we load a separate page as a modal (yay, right?)

The embedded page uses window.parent.postMessage(messageString, '*') to signal actions have been completed.

I want to use stenciljs's @Listener

I have a working modal with an iframe to the other page, using the old school window.addEventListener('message', myMessageHandlingDelegate).

however, I really would like to use the @Listener attribute/decorator to handle the result of the posted message. I tried @Listener('message') but the code was not added....

is there away to get a stenciljs listener to catch messages posted from child Iframes?


Solution

  • The @Listen decorator is used to add listener to JavaScript custom events (https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent) or to events emitted by a Stencil child component. That means that you can't use Message API (using window.postMessage or listening to the message event) with that decorator. You can still use the addEventListener to the message event like you indicated in the question.