Im migrating a lightning component that has a VF iframe that is using the postMessage function
When I try to use the same function in LWC I get a the following error:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://dev123.lightning.force.com') does not match the recipient window's origin ('https://dev123.visualforce.com').
tried a couple ways with the same result
Here is my lwc code
html
<template>
<lightning-button onclick={sendData}></lightning-button>
<iframe id="vfFrame" src={vfHost} height="100%" width="100%"> .
</iframe>
</template>
js
import { LightningElement, api} from 'lwc';
export default class orderBooks extends LightningElement {
@api books = [];
vfHost = 'https://velocity-energy-3703-dev-ed--c.visualforce.com/apex/iframe';
origin = 'http://velocity-energy-3703-dev-ed--c.visualforce.com';
constructor() {
super();
this.template.addEventListener('message', function(event) {
console.log(event);
if (event.origin !== origin) {
// Not the expected origin: Reject the message!
return;
}
// Handle the message
console.log(event.data);
}, false);
}
// adding a callback to see if this works
connectedCallback(){
this.template.addEventListener('message', function(event) {
console.log(event);
if (event.origin !== origin) {
// Not the expected origin: Reject the message!
return;
}
// Handle the message
console.log(event.data);
}, false);
}
sendData(){
var message = 'testing';
this.template.querySelector('iframe').contentWindow.postMessage(message, origin);
}
VF
<apex:page showHeader="false" standardStylesheets="false" sidebar="false" applyHtmlTag="false" applyBodyTag="false" docType="html-5.0" >
<script>
var lexOrigin = "https://velocity-energy-3703-dev-ed.lightning.force.com";
window.addEventListener("message", function(event) {
console.log('Origin '+ event.origin);
console.log('data '+ event.data);
if (event.origin !== lexOrigin) {
// Not the expected origin: reject message!
return;
}
});
</script>
</apex:page>