How to get a dom element in a new window?

You’ve done it right, but you do need to be sure to use onload (or poll), because it takes a moment for the page to get loaded in the new window.

Here’s a full working example: Live Copy | Source

(function() {

  document.getElementById("theButton").onclick = function() {

    var novoForm = window.open("http://jsbin.com/ugucot/1", "wFormx", "width=800,height=600,location=no,menubar=no,status=no,titilebar=no,resizable=no,");
    novoForm.onload = function() {
      var w = novoForm.innerWidth;
      var h = novoForm.innerHeight;
      novoForm.document.getElementById("monitor").innerHTML = 'Janela: '+w+' x '+h;
    };
  };
})();

I’m wondering if it’s some security restriction or am I missing something…

Not in your example as shown, no, because the page is clearly being loaded from the same origin. If the URL were from a different origin, then yes, you’d be running into the Same Origin Policy, which prohibits cross-origin scripting. You can relax that via the document.domain property, having both the window containing the code above and the window being loaded setting document.domain to the same value. From the link above:

If two windows (or frames) contain scripts that set domain to the same value, the same-origin policy is relaxed for these two windows, and each window can interact with the other. For example, cooperating scripts in documents loaded from orders.example.com and catalog.example.com might set their document.domain properties to “example.com”, thereby making the documents appear to have the same origin and enabling each document to read properties of the other.

More about document.domain can be found on MDN. Note that it only works where both documents share a common parent domain, e.g., so it works for app1.example.com and app2.example.com if they both set to example.com, but not for example1.com and example2.com because they have not common value they can set.

Leave a Comment