How can I access the dom tree of child window?
Asked Answered
S

4

18

I open a new window using the following code:

purchaseWin = window.open("Purchase.aspx","purchaseWin2", "location=0,status=0,scrollbars=0,width=700,height=400");

I want to access the dom tree of the purchaseWin, e.g.

purchaseWin.document.getElementById("tdProduct").innerHTML = "2";

It doesn't work. I can only do this:

purchaseWin.document.write("abc");

I also try this and it doesn't work too:

 $(purchaseWin.document).ready(function(){

     purchaseWin.$("#tdProduct").html("2");

   });

What should I do?

Southey answered 11/8, 2009 at 5:26 Comment(0)
T
16

With jQuery, you have to access the contents of the document of your child window:

$(purchaseWin.document).ready(function () {
  $(purchaseWin.document).contents().find('#tdProduct').html('2');
});

Without libraries, with plain JavaScript, you can do it this way:

purchaseWin.onload = function () {
  purchaseWin.document.getElementById('tdProduct').innerHTML = '2';
};

I think that the problem was that you were trying to retrieve the DOM element before the child window actually loaded.

Tamarind answered 11/8, 2009 at 5:38 Comment(3)
The plain Javascript version works. But jQuery version fails. I need to run the jQuery code manually in parent window to work.Southey
Works in IE (not firefox): $(purchaseWin.document).ready(function () {$(purchaseWin.document).contents().find('#tdProduct').html('2');}); Works in FF (not IE): purchaseWin.onload = function () {$(purchaseWin.document).contents().find('#tdProduct').html('2');};Southey
See Gunni's response, using $(purchaseWin).load for the jQuery option works whereas the document ready event didn't.Photon
B
12

Maybe the load event of jQuery works for you as this worked for me in a similar Problem, whereas the ready event did not work:

$(purchaseWin).load(function(){
    purchaseWin.$("#tdProduct").html("2");
});
Blat answered 19/2, 2013 at 16:9 Comment(2)
New is that i use the .load event while the accepted answer uses the .ready event. For me that made a difference.Blat
This is the only answer that gave me access to the dom of the child.Stefanstefanac
H
11

You cannot access the document of a child window if you load a page that does not belong to the domain of the parent window. This is due to the cross-domain security built into Javascript.

Hockett answered 15/3, 2013 at 16:41 Comment(0)
B
1
(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;
    };
  };
})();
Brew answered 30/8, 2017 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.