5

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';

connectedCallback(){
    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);
        }
    });
}

openIFrameHandler(event){
    var parameters = event.detail;
    this.template.querySelector('c-child-component')
        .formIFrameUrl(parameters);
    this.iFrameClassName = 'showIFrame';
}

Parent component markup:

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

Child component js:

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

Child component markup:

<template>
<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?

5

UPDATE:

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.