Last updated: October 3, 2022.
open method on the global
To open a URL in a new window, simply pass in the URL to
window.open as an argument in string format:
The new window doesn't have to open a URL.
You can code the content of the new window yourself:
const newWindow = window.open(''); newWindow.document.write("This text is the content of the new page!");
Just like an ordinary window, you have full access to the DOM of a new window instance.
To access it, you must save a reference to the new window instance in a variable when creating it.
document object is then accessible on it:
const newWindow = window.open(''); const title = newWindow.document.createElement('h1'); const content = newWindow.document.createElement('p'); title.textContent = "Hi, from a new window"; content.textContent = "You can still control me from the original window!"; newWindow.document.body.appendChild(title); newWindow.document.body.appendChild(content);
As is the case with all methods on the
window object, you can omit the reference to it when calling the
Optional second parameter: opening behaviour
You can change the opening behavior of the new window by adding an optional second parameter:
|Parameter value||Opens new window in:|
|_blank||A new tab or browser window|
|_self||The same browser window (replaces current page)|
|_parent||The next frame up, if executed inside a nested frame|
|_top||The global browser window, ignoring any nested frame structure|
For example, to open a new window instance that replaces the current window:
If no second argument is specified, the default behavior is
_blank (window opens in new tab).
If you are happy with this behavior, you can use the second argument as an opportunity to enter a reference name for the new window:
Referencing a new window
Optional third parameter: dimension and screen placement
You can also specify the dimensions and placement of a new window on a user's screen.
For this, you can enter some of the following information in the third argument position in a comma-separated list:
|width=pixels||Width of new window|
|height=pixels||Height of new window|
|left=pixels||Spacing from the left-hand side of the screen|
|top=pixels||Spacing from the top of the screen|
Closing a window
If you have opened a new window with
window.open() and saved a reference to it, you can close it from the original window.
To do so, call the
close() method on the reference to the newly opened window.
The following example includes a time delay so the new window is open for five seconds before it is closed: