0

I'm trying to post a message when the iframe is loaded in the page, but it doesn't work on iframe.onload or iframe.addEventListener('load', it only works with using setTimeout

const iframe = document.getElementById('iframe')

const postFrameMessage = () => {
    const params = {test: 'duh', ping: 'pong'}
    iframe.contentWindow.postMessage({parentParams: params }, "*")
}

//Dont work, no response back
postFrameMessage()

//Dont work, no response back
iframe.onload = () => postFrameMessage()

//Dont work, no response back
iframe.addEventListener('load', () => postFrameMessage() )

//Dont work, no response back
document.addEventListener('DOMContentLoaded', postFrameMessage() )

//Dont work, no response back
window.onload = () => postFrameMessage()

// Works fine and i get a response from the iframe
setTimeout(() => postFrameMessage(), 2000)

How do I avoid using setTimeout and trigger the postMessage when the iframe is loaded on the page? and maybe a bit of explanation why onload, load and DOMContentLoaded doesn't work

SymmetricsWeb
  • 586
  • 6
  • 20
  • This seems to be relevant: https://stackoverflow.com/questions/3142837/capture-iframe-load-complete-event#3142939. I suspect point 3 applies; that the iframe is done loading before the event handler has been attached. – padeso Mar 31 '23 at 14:43

0 Answers0