I am trying to use the postMessage API to receive and send data to an embedded iframe in my wix site. The desired end result is being able to pass utm params from wixLocation to the iframe. I am receiving data on other sites using this iframe so the problem seems to be with the wix/velo code. Would appreciate any help on this.
here is the velo code:
$w.onReady(function () { $w("#html1").onMessage( (event) => { console.log(`Message received by page code: ${event.data}`); } ); } );
and in the HTML component (React code):
useEffect(() => {
window.parent.postMessage('message from iframe', '*');
}, []);
If you want to use React (or other frameworks, or plain JS web components) you might want to consider using the Wix Custom Element. Take a look at the Custom Element examples to see how they're used.
Maybe you post it to the page before the $w is ready. try to look into it
Does other React functionality work for you there?
Did you take a look into the VELO-API-Docs?
/* * * * * * * * * * * * * * * * * * * * * * * * * * Paste the following into the HTML Component: * * * * * * * * * * * * * * * * * * * * * * * * * * <!doctype html> <html> <head> <script type="text/javascript"> function init () { // when a message is received from the page code window.onmessage = (event) => { if (event.data) { console.log("HTML Code Element received a message!"); insertMessage(event.data); } } } // display received message function insertMessage(msg) { document.getElementById('demo').innerHTML = msg; sendReturnMessage("Message from the HTML Component!"); } // send message to the page code function sendReturnMessage(msg) { window.parent.postMessage(msg, "http://mysite.com"); } </script> </head> <body onload="init();" style="background-color:lightgray;"> <h1>HTML Component Test</h1> <p id="demo">Message will go here</p> </body> </html> * * * * * * * * * * * * * * * * * * * * * * * * * * This is the page code: * * * * * * * * * * * * * * * * * * * * * * * * * */ $w.onReady(function () { // when a message is received from the HTML Component $w("#myHtmlComponent").onMessage( (event) => { console.log(`Message received by page code: ${event.data}`); } ); } ); export function messageSendButton_onClick() { // send message to the HTML Component $w("#myHtmlComponent").postMessage("Message from page code!"); }
Expand your code inside your HTML-Component, like shown in the EXAMPLE.