2

I have opened a new window with JavaScript:

var newwin = window.open('','preview','width=600,height=500');

Now I want to write some JavaScript to the window:

newwin.document.write("<script type='text/javascript'>alert('Hi!');<" + "/script>");
newwin.document.close();

However, the script never gets executed. Am I doing something wrong?


Update: Okay, now I got part of it working. Here is the current code I have:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type='text/javascript'>

function SetContent()
{
    $('#content').html('New Text');
}

function dowin()
{
    var newwin = window.open('','preview','width=600,height=500');

    newwin.document.write('<div id="content"></div><b>This should be replaced...</b>');
    newwin.document.close();

    var script = newwin.document.createElement("script");
    script.type = "text/javascript";
    script.src = 'jquery.js';
    newwin.document.body.appendChild(script);

    var script2 = newwin.document.createElement("script");
    script2.type = "text/javascript";
    script2.textContent = "(" + SetContent + ")();";
    newwin.document.body.appendChild(script2);
}

</script>
</head>
<body>
<button onclick='dowin();'>Open</button>
</body>
</html>

It's supposed to change the content of the div but as you can see, it doesn't.

tshepang
  • 12,111
  • 21
  • 91
  • 136
Nathan Osman
  • 71,149
  • 71
  • 256
  • 361

2 Answers2

1

Your code running ok on my Firefox 3.7, Opera 10, and IE6, but you could try different approach by using DOM functions.

var newwin = window.open('','preview','width=600,height=500');

function sayHi(){
    alert('Hi!');
}

var script = newwin.document.createElement("script");
script.type = "text/javascript";
script.textContent = "(" + sayHi + ")();";
newwin.document.body.appendChild(script);

If its not working, you should double check popup blockers or javascript blockers on your browser.

YOU
  • 120,166
  • 34
  • 186
  • 219
  • What if I wanted to reference an external .js file in the new window? – Nathan Osman Apr 23 '10 at 06:55
  • 1
    @George, Try `script.src = 'http://external.com/some.js'` instead of `.textContent` – YOU Apr 23 '10 at 06:58
  • @George, I think `$('#content')` will not run because jQuery not finishing loading on child window. you might need to run it on `onload` of child window. – YOU Apr 24 '10 at 05:14
0
function SetContent() 
{ 
    $(newwin).find('#content').html('New Text'); 
} 
David
  • 2,785
  • 1
  • 16
  • 8