sbs
sbs

Reputation: 1311

How to call a javascript function in an opened child window

I have a parent html file and want the user to click something which should then open a new window (or tab) containing the (dynamically generated) contents of a div in the parent (which is hidden in the parent).

From my reading here and elsewhere something like this should work:

parent.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Parent</title>
        <script src="/js/jquery-1.11.0.min.js"></script>
    </head>
    <body>
        <div id="from">
            html from parent
        </div>

        <div id="launcher">
            launch child
        </div>

        <script type="text/javascript">
            $("#launcher").click(function() {
                var child = window.open('child.html', '_blank', '', false);
                if (child) {
                    var html = $("#from").html();
                    //window.setTimeout(child.addHTML(html), 5000);
                    child.addHTML(html);
                }
                else {
                    alert('Please allow popups for this site');
                }
            });
        </script>
    </body>
</html>

child.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Child</title>
        <script src="/js/jquery-1.11.0.min.js"></script>
    </head>
    <body>
        <div id="to"></div>

        <script type="text/javascript">
            function addHTML(html) {
                $('#to').html(html);
            }
        </script>
    </body>
</html>

However, regardless of using the commented-out setTimeout (incase the child hadn't loaded yet before calling the child's function), I get this error (in Safari, similar in Chrome) immediately:

'undefined' in not a function (evaluating 'child.addHTML(html)')

What am I doing wrong? Is there a better way to achieve my goals?

Upvotes: 0

Views: 1783

Answers (2)

micha
micha

Reputation: 1238

if the goal is only to add the content and not to call a function u can do it this way

if (child) {
    child.addEventListener('load', function () {
        var html = $("#from").html();
        $('#to',child.document).html(html)
    });
}else {
    alert('Please allow popups for this site');
}

Upvotes: 1

Tob&#237;as
Tob&#237;as

Reputation: 6287

The first parameter of window.setTimeout should be the function to execute.

Try this:

        if (child) {
            var html = $("#from").html();
            window.setTimeout(function(){child.addHTML(html);}, 5000);
        }

I built a small example:: http://jsfiddle.net/rt19hv7v/

Upvotes: 1

Related Questions