javascriptwindowcommunicationonreadystatechange

Javascript window write callback


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.');
};

Solution

  • 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;