June 4, 2000 - Writing to a New Window | WebReference

June 4, 2000 - Writing to a New Window

Yehuda Shiran June 4, 2000
Writing to a New Window
Tips: June 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

The following script shows a typical scenario for opening a window and writing a new document to it:

var win = window.open("", "win", "width=300,height=200"); // a window object
win.document.open("text/html", "replace");
win.document.write("<HTML><HEAD><TITLE>New Document</TITLE></HEAD><BODY>Hello, world!</BODY></HTML>");
win.document.close();

The first statement opens a new window with an empty document (""). The returned value is assigned to a variable named win. We then use the new window's document object, win.document, to write some HTML to the new window. The "replace" specification is necessary, because we don't want the blank page to have an entry in the History list.

Since we're dealing with the same document object, we might as well assign it to another variable:

var win = window.open("", "win", "width=300,height=200"); // a window object
var doc = win.document;
doc.open("text/html", "replace");
doc.write("<HTML><HEAD><TITLE>New Document</TITLE></HEAD><BODY>Hello, world!</BODY></HTML>");
doc.close();

We can also use the with statement:

var win = window.open("", "win", "width=300,height=200"); // a window object
with (win.document) {
  open("text/html", "replace");
  write("<HTML><HEAD><TITLE>New Document</TITLE></HEAD><BODY>Hello, world!</BODY></HTML>");
  close();
}

Click the following button to run the script:

"); close(); } } // -->

Learn more about manipulating windows in Tutorial 1, Working with Windows.