Writing to a window

JavaScript FAQ | JavaScript Windows FAQ  

Question: How do I write script-generated content to another window?

Answer: To write script-generated content to another window, use the method winRef.document.write() or winRef.document.writeln(), where winRef is the window reference, as returned by the window.open() method.

To make sure that your script's output actually shows up in the other window, use winRef.document.close() after writing the content. As an example, consider the following function that opens a new window with the title Console and writes the specified content to the new window.

writeConsole('Hello from JavaScript!');
function writeConsole(content) {
 top.consoleRef=window.open('','myconsole',
  'width=350,height=250'
   +',menubar=0'
   +',toolbar=1'
   +',status=0'
   +',scrollbars=1'
   +',resizable=1')
 top.consoleRef.document.writeln(
  '<html><head><title>Console</title></head>'
   +'<body bgcolor=white onLoad="self.focus()">'
   +content
   +'</body></html>'
 )
 top.consoleRef.document.close()
}
If you try the above example in Internet Explorer or Firefox, you might notice that after you write something to the console several times, the console window will allow you to navigate back and forth in the output's history. This is not always a desired feature. If you would like to output the new content without creating a new history entry, add the following operator after opening the window (and before the first write):
docRef = top.winRef.document.open("text/html","replace");
Here winRef is the window reference returned by the window.open() method, and docRef is a global variable in which the script stores the reference to your new document.

Note: Some browsers, e.g. Google Chrome or Safari, won't allow the back/forward navigation in the secondary window in this example, with or without document.open("text/html","replace").

Copyright © 1999-2012, JavaScripter.net.