I am creating an application that will be used on other websites through an iframe. I am trying to create a js script that the host site will attach to their html page. I am able to create the iframe dynamically with javascript. But I also need to send information from the host site to the iframe, this data will authenticate the host site. I am able to send this using iframe.contentWindow.postMessage when attached to a button. But when I try to attach it to a onload event listener I get the error Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('IFRAME DOMAIN') does not match the recipient window's origin ('null'). the domains will be different, how can I get this to work at first load?
const buildIframe = (element) => {
const terpliIFrame = document.createElement("iframe");
terpliIFrame.setAttribute("src", "https://flutter-plugin-1b70a.web.app/#/");
terpliIFrame.style.width = "340px";
terpliIFrame.style.height = "600px";
terpliIFrame.style.zIndex = "2147483647"
terpliIFrame.style.overflow = "hidden";
terpliIFrame.style.position = "fixed";
terpliIFrame.style.bottom = "5px";
terpliIFrame.style.right = '10px';
terpliIFrame.setAttribute("allowtransparency", "true")
terpliIFrame.setAttribute("frameBorder", "0")
// I would like to send the postMessage here before I append it to the page
element.appendChild(terpliIFrame);
return terpliIFrame;
}
I am able to have it work when I attach it to a button click
if (addToCartButton) {
addToCartButton.addEventListener("click", () => {
iframe.contentWindow.postMessage(JSON.stringify({url: originURL, retailToken: retail}) , "DOMAIN")
})
}
When I use this function:
iframe.onload = () => {
console.log("hello")
iframe.contentWindow.postMessage(JSON.stringify({url: originURL, retailToken: retail}) , "Domain")
}
I do not get an error, it console logs hello, bit does not properly send it to the iframe
Can anyone help?