Search code examples
javascriptpopupreadystate

Javascript pop-up window document is never "ready"


I'm using Javascript to open a blank window, populate it with the bare minimum and inject a script tag to include JQuery, but the window property readyState never gets past loading, therefore JQuery never triggers. Here is the demo on jsFiddle. I can't figure out why the popup window doesn't update its readyState.

var popup = window.open("", "popup", "height=500,width=700");
var doc = popup.document;
doc.write("<!doctype html><html><head></head><body></body></html>");
var script = doc.createElement("script");
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
script.onload = function() {
  console.log(doc.readyState);
  popup.$(document).ready(function() {
    console.log(doc.readyState);
  });
}
doc.getElementsByTagName("head")[0].appendChild(script);

Here is similar code without JQuery--same problem with the readyState window property never going beyond "loading".

var popup = window.open("", "popup", "height=500,width=700");
var doc = popup.document;
doc.write("<!doctype html><html><head></head><body></body></html>");
console.log(doc.readyState);

Solution

  • If you never set the URL, then the ready state isn't going to change. It will either be "initialized" or "loading" - depending on your browser. You can see this update by setting the document.location in the console window of your popup window like the command below:

    console.log(document.readyState);
    document.location = "http://yourdomain.com";
    console.log(document.readyState);
    

    If you sent the location to a domain other than your domain, you will not have security to modify the window object. A way to get around this is to use an iframe and set the source - like so:

    var nw = window.open('', "MyWindowID", "fullscreen=no, toolbar=no, menubar=no,status=no,location=no");
    var html = '<iframe id="document-{aid}" style="width:100%;height:100%;" src="http://www.google.com"></iframe>';
    nw.document.write(html);
    nw.focus();
    

    See: https://stackoverflow.com/a/1443839/1220302

    A note on this is to try wrapping your popup in $(popup) and hook the ready event.

    This should work for you:

    var popup = window.open("", "popup", "height=500,width=700");
    var doc = popup.document;
    doc.write("<!doctype html><html><head></head><body></body></html>");
    var script = doc.createElement("script");
    script.type = "text/javascript";
    script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";    
    $(popup).ready(function(){
        console.log('loaded');
    });