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?

Billy
  • 15,516
  • 28
  • 70
  • 101

4 Answers4

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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 1
    The plain Javascript version works. But jQuery version fails. I need to run the jQuery code manually in parent window to work. – Billy Aug 11 '09 at 06:03
  • 3
    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');}; – Billy Aug 11 '09 at 06:30
  • 1
    See Gunni's response, using $(purchaseWin).load for the jQuery option works whereas the document ready event didn't. – Luke Dec 04 '13 at 14:18
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");
});
Gunni
  • 519
  • 5
  • 14
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.

Deven Kalra
  • 119
  • 1
  • 2
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;
    };
  };
})();
Dan
  • 3,246
  • 1
  • 32
  • 52
Guru
  • 2,739
  • 1
  • 25
  • 27