Estoy creando una aplicación que se utilizará en otros sitios web a través de un iframe. Estoy tratando de crear un script js que el sitio host adjuntará a su página html. Puedo crear el iframe dinámicamente con javascript. Pero también necesito enviar información desde el sitio host al iframe, estos datos autenticarán el sitio host. Puedo enviar esto usando iframe.contentWindow.postMessage cuando se adjunta a un botón. Pero cuando trato de adjuntarlo a un detector de eventos de carga, aparece el error Error al ejecutar 'postMessage' en 'DOMWindow': el origen de destino proporcionado ('IFRAME DOMAIN') no coincide con el origen de la ventana del destinatario ('null'). los dominios serán diferentes, ¿cómo puedo hacer que esto funcione en la primera carga?
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;}
Puedo hacer que funcione cuando lo adjunto a un clic de botón
if (addToCartButton) { addToCartButton.addEventListener("click", () => { iframe.contentWindow.postMessage(JSON.stringify({url: originURL, retailToken: retail}) , "DOMAIN") })}
Cuando uso esta función:
iframe.onload = () => { console.log("hello") iframe.contentWindow.postMessage(JSON.stringify({url: originURL, retailToken: retail}) , "Domain")}
No recibo un error, la consola registra hola, el bit no lo envía correctamente al iframe
¿Alguien puede ayudar?