views:

69

answers:

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"&gt;
<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.

+1  A: 

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.

S.Mark
What if I wanted to reference an external .js file in the new window?
George Edison
@George, Try `script.src = 'http://external.com/some.js'` instead of `.textContent`
S.Mark
`textContent` won't work in IE...
J-P
@J-P, so `.innerHTML`? looking into it now. thanks
S.Mark
@S.Mark - I updated the question with my progress so far...
George Edison
@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.
S.Mark
A: 
function SetContent() 
{ 
    $(newwin).find('#content').html('New Text'); 
} 
David
This doesn't work.
George Edison
OK, possibly then:$(newwin.document).find('#content').html('New Text');
David
@David: Nope, no dice.
George Edison