tags:

views:

52

answers:

3

Could somebody explain why the following simple script doesn't work in Firefox and how can I fix it?

<script type="text/javascript">
var w = window.open("a.php");
w.document.write("hello");
</script>

Thanks much

A: 

I'm pretty sure you can't read/ write files using javascript because it's a client side language? I may be completely wrong though!

EDIT:

Try this code:

var new_window, new_window_content = [];
new_window_content.push('<html><head><title>New Window</title></head>');
new_window_content.push('<body>New Window</body>');
new_window_content.push('</html>');
new_window = window.open("", "", "status,height=200,width=200");
new_window.document.write(new_window_content.join(''));

Cheers, Sean

seanxe
Hey, don't you read what is asked here? Read the question carefully before answering.
Darin Dimitrov
sorry - the title should of been along the lines of "open a window and write content into it". The current title on a programming forum suggests otherwise.
seanxe
A: 

To the others posting answers here: he is not trying to open a file and write to it - it is impossible in javascript in a browser. What he is instead trying to do with the w.document.write is to write to the end of the web page he has just opened in a browser.

Google Chrome says this code fails as:

>>> var w = window.open("http://www.google.co.uk");
undefined
>>> w.document.write("lol");
TypeError: Cannot call method 'write' of undefined

You first need to open the document stream by using document.open() - this will add a write function in w.document:

<script type="text/javascript">
var w = window.open("a.php");
w.document.open();
w.document.write("hello");
w.document.close();
</script>
Callum Rogers
I voted this down because the document.write() function is not what he should be using here. See Dawn's answer below for the better way, i.e. adding "hello" to a DOM element in the new page.
Steve Claridge
+2  A: 

(edited to make the code sample display better)

DOM Scripting is more up to date and more robust.

e.g.

var w = window.open("a.php");
w.onload = function(){//you could also use dom ready rather than onload but that is a longer script that I've not included here
  var body = w.document.getElementsByTagName("body")[0];
  body.appendChild(document.createTextNode("bar"));
}
Dawn
This is the right way to do it.
Steve Claridge