6

I'm trying to perform operations on the DOM of a popup window, but for some reason the ready event fires immediately for the popup, before there's anything in the DOM.

I know that jQuery can access the DOM of the popup window by using context, and that I can manage to do it by using setTimeout to delay any action until a reasonable amount of time has passed.

http://jsfiddle.net/GVcjn/

(function ($) {
    $(function () {
        var popup = window.open('/test');
            // JSFiddle 404 page

        $(popup.document).ready(function () {
            // Should fire when the DOM of the 404 page has loaded...

            $('h2', popup.document).css('color', '#FF0000');
                // Change the color of the header to red.

            console.log($('h2', popup.document).length);
                // Should log 1
                // Logs 0, though, because this function fires immediately, before the DOM loads.
        });

        setTimeout($.proxy(function () {
            // This will definitely fire after the DOM of the 404 page is loaded.

            var popup = this;
            $('h2', popup.document).css('text-decoration', 'underline');
                // This works, because it waited long enough.
                // But I don't want to guess how long it will take the DOM to load....
        }, popup), 5000);
            // After 5 seconds...
    });
})(jQuery);

Also, I know it's not jQuery's fault. If I add console.log(popup.document.readyState); immediately after var popup = window.open('/test');, it prints complete. Why, though?

Any advice?

Thanks!

M Miller
  • 5,364
  • 9
  • 43
  • 65

1 Answers1

7

Have you tried this?

popup.onload = function () {
  //lot of things
};

With jQuery load, according to the documentation http://api.jquery.com/load-event/ is:

$(popup).load(function() {
  // things
});

This question answer something similar too: How can I access the dom tree of child window? Hope it helps you

Community
  • 1
  • 1
joseramonc
  • 1,811
  • 2
  • 21
  • 40
  • I would've preferred the ready event since window load isn't fired until all resources have finished loading instead of just the DOM... but that doesn't seem possible. This will do the trick. Thank yoU! – M Miller Oct 30 '13 at 15:46
  • 1
    Note: `$(popup).load(function() {...});` is deprecated as of 1.8 in favour of: `$(popup).on('load', function(){...});` – Glenn Jan 29 '17 at 18:20