I am having trouble setting up an eventListener for my LWC component to listen messages received from an embedded iFrame.

I have a parent component where I have set the event listener in connectedCallback hook as follows:

export default class MainComponent extends LightningElement {
@api recordId;
@track iFrameClassName = 'hideIFrame';

    window.addEventListener("message", function(event){
        console.log("Message received from origin: " + event.origin);
        if(event.origin === "https://my.domain.com"){
            // Close iframe
            this.iFrameClassName = 'hideIFrame';
            console.log('CLASSNAME: ' + this.iFrameClassName);

    var parameters = event.detail;
    this.iFrameClassName = 'showIFrame';

Parent component markup:

<lightning-layout horizontal-align="center">
    <c-child-component i-frame-class-name={iFrameClassName}></c-child-component>
<c-product-table recordid={recordId} onopeniframe={openIFrameHandler}></c-product-table></template>

Child component js:

export default class ChildComponent extends LightningElement {
  @track url;
  @api iFrameClassName
     this.url = 'www.my.domain.com/' + someparameters;

Child component markup:

<iFrame class={iFrameClassName} src={url}></iFrame></template>

The child-component iFrame is shown when openIFrameHandler is fired but when a message is received from the IFrame and the iFrameClassName is set to 'hideIFrame' the classname in the child-component won't change.

As a matter of fact, the console logging in the eventListener is writing 'CLASSNAME: hideIFrame' but the tracked property is NOT changed, why is this?

I have also tried to set the eventhandler in the component constructor but it did not help.

How do I setup the event listener so that the iFrameClassName property is set when message is received?

I have previously worked with aura lightning components and this worked perfectly when set up in the parent components doInint method...

Any ideas?

1 Answer 1



I finally managed to find a solution to this problem. Because my eventlistener was declared using a normal function the context of 'this' was different to my class.

The solution was to use an arrow function like: window.addEventListener("message", (event) => {}.

This solved the issue.

  • Thanks had the same issue & this resolved for me.
    – Jim
    Jul 3, 2020 at 4:53
  • What about removeEventListner in this case? Did you write it in the callback function and does it work?
    – Sarang
    Jul 8, 2021 at 9:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .