2

Is there a way to for a parent to know when a child window has loaded it's content? Without any script in the child.

Here is my current code:

var printWindow = window.open('', '_blank');
printWindow.document.write(clonedElement.html());
printWindow.onreadystatechage = function() {
    console.log('this does not work.');
};
user59388
  • 159
  • 1
  • 10

2 Answers2

2

You have the same events that fire on window, so you could get the load event if you opened the page with the html there already, e.g.

var b = new Blob([clonedElement.html()], {type: 'text/html'}),
    uri = URL.createObjectURL(b),
    printWindow;
printWindow = window.open(uri, '_blank');
printWindow.addEventListener('load', function () {
    URL.revokeObjectURL(uri); // release these
    b = null;                 // from memory
    // do something else
});

Please be aware that there will be a race condition here (though you'll almost always win it, i.e. if the page loads and the event fires between opening and adding the listener)


Alternatively, without the race

var b = new Blob([clonedElement.html()], {type: 'text/html'}),
    uri = URL.createObjectURL(b),
    printWindow = window.open('', '_blank');
printWindow.addEventListener('load', function () {
    URL.revokeObjectURL(uri); // release these
    b = null;                 // from memory
    // do something else
});
printWindow.location = uri;
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • "if you opened the page with the html there already" But what if you're using `printWindow.document.write()` (as per the question) ? – Brad Kent Mar 30 '18 at 21:21
0

It seems that you might be facing a cross domain policy problem here. The parent and child pages have to be hosted in the same domain. Browsers, like chrome for instance, won't allow it where as FF can be more lenient in some cases. You should look into 'enabling CORS' and this link should help you as well: Waiting for child window loading to complete

Community
  • 1
  • 1
Estarossa
  • 585
  • 4
  • 21