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?