Chapsterj
Chapsterj

Reputation: 6625

How to append a chunk of html to a loaded html page using window.open() method

I'm trying to append a chunk of html to a loaded html page via window.open() method. for this example the chunk of html will be a string.

var w = window.open('mypage.html, 'windowname', 'scrollbars=yes,location=no,toolbar=no,status=no,width=500,height=550,left=300,top=50');
var htmlChunk = '<span>bla bla</span>'
 $(w.document.body).append( htmlChunk );

$(w.document.body) doesn't seem to be able to get to the body tag on the mypage.html inside the popup.

I also tried using a ready method.

 $(w.document.body).ready(function(){
         $(this).find('body').append(htmlChunk);
     });

This didn't work either it was appending it to the window below the popup.

Just to be clear here i'm not looking to add any JS to mypage.html directly. I need to be able to access the popup mypage.html body tag and append a chunk of html to that. My setup, I have a js file inside a main.html page. In the main.html page I have link that has a click event on it which is setup inside the js file. This is where I call the popup and I capture a block of html from the main.html page to append to the mypage.html inside the popup.

Upvotes: 2

Views: 1928

Answers (3)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146540

You can do something like this:

$(w).on("load", function(){
    $("body", w.document).append( htmlChunk );
});

The onload event handler makes the code wait until the new window has been created, and using w.document as jQuery's second argument sets the context on the new window. You cannot run a jQuery instance from the child window because it doesn't load jQuery.

Upvotes: 4

Deep Sharma
Deep Sharma

Reputation: 3483

<script type="text/javascript">
    $(document).ready(function () {
        var output = "data";
        var OpenWindow = window.open("mypage.html", "mywin", '');
        OpenWindow.dataFromParent = output; // dataFromParent is a variable in mypage.html
        OpenWindow.init();
    });
</script>

in mypage.html:

<script type="text/javascript">
    var dataFromParent;    
    function init() {
        document.write(dataFromParent);
    }
</script>

If you need the code to run after the new window's DOM is ready try this:

var OpenWindow = window.open("mypage.html", "mywin", '');
$(OpenWindow.document.body).ready(function() {
    $(OpenWindow.document.body).append('<p>hi</p>');
});

Upvotes: 0

2rsvold
2rsvold

Reputation: 17

If I'm not mistaking the $()-operator in jQuery should run when the page is "ready". So you could try to simplify your code a bit?

I would do it like this:

$(function(){
    $("body").append("This is the string you send in");
});

Upvotes: 0

Related Questions