1

Is there a way to know if parent window has loaded from within iframe?

I want to run a function which is in iFrame but I need to run it after all the parent windows are loaded and the event listener will be inside the iframe.

I tried the following but it runs before parent windows are loaded.

window.addEventListener('load', function () {
alert("It's loaded!")
});
John Doe
  • 129
  • 7

1 Answers1

0

One way would be to add the iframe dynamically:

parent:

window.addEventListener('load', function () {
   var iframe = document.createElement('iframe');
   
   iframe.src = "https://www.example.com";

   document.body.appendChild(iframe);
});

iframe:

window.addEventListener('load', function () {
   alert('hello world!');
   //doSomethingUseful();
}

This way, you could be certain that they will load in a specific order. However, as they'd be loading in series, the increase in total page load time could become noticeable.


Alternatively, you could use this approach. This one may not work as is, if one page happens to finish loading before the other. If you do opt for this approach, it may be necessary to communicate in both directions so that the first page to load finds out when the second page has loaded. That may look like this:

parent:

newEvent();
window.document.addEventListener('myCustomEventI', newEvent, false);

function newEvent() {
   var data = { loaded: true }
   var event = new CustomEvent('myCustomEventP', { detail: data })
   window.parent.document.dispatchEvent(event);
}

iframe:

newEvent();
window.document.addEventListener('myCustomEventP', handleEvent, false);

function newEvent() {
   var data = { loaded: true }
   var event = new CustomEvent('myCustomEventI', { detail: data })
   window.parent.document.dispatchEvent(event);
}

function handleEvent(e) {
  alert('both loaded!');
  //doSomethingUseful();
}
sbgib
  • 4,666
  • 3
  • 12
  • 21