How to use postMessage from an iframe with different origin?

I am trying to embed in an iframe a Hubspot form and redirect the user once the form is completed.
My code is the following:

Embedded form in the iframe which display as expected:

Code in parent page:
import wixLocation from ‘wix-location’;

$w.onReady(function () {
$w(“#iframeid”).onMessage( (event) => {
wixLocation.to(“/redirect_page”)
} );
});

I get the following error message in the console:


Which means that window.parent is undefined. How do you properly use postMessage from an iframe with different origin?

I guess, the needs to be inside the or .

I changed the position of the script to be inside the tag but it didn’t help with the problem.

Try to use window.parent.postMessage(“msg”, “*”) and do a test.
Did you import the hubspot scripts?
Test the function outside the form create function.

console.log the event onMessage.

You should see the window object on Dev Tools log (Chrome F12).

Did you see the section on Messaging ?

Thank you, I tried window.parent.postMessage(“msg”, “*”). I was testing in the preview which has a different url than the production website and that was blocking the messaging. I still get the javascript error but the Messaging works so I imagine it is unrelated to my script.