Billy
Billy

Reputation: 15706

How can I access the dom tree of child window?

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?

Upvotes: 18

Views: 38584

Answers (4)

Guru
Guru

Reputation: 2857

(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;
    };
  };
})();

Upvotes: 1

Gunni
Gunni

Reputation: 519

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");
});

Upvotes: 12

Deven Kalra
Deven Kalra

Reputation: 119

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.

Upvotes: 11

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827694

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.

Upvotes: 16

Related Questions