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