How to open a new browser window from JavaScript

OpenJavaScript 0
Reading Time: 2 minutes 🕑

Last updated: August 21, 2022.

We can easily open a new browser window from JavaScript by applying the open method to the global window object at any point in our code.

We can open a URL in a new window:

window.open("https://www.openjavascript.info")
// Opens a new instance of this website

Or code the content ourselves:

const newWindow = window.open(""); 
// Opens an empty window

newWindow.document.write("This text appears on the new page."); 
// New window available through newWindow

By default, the content of the first parameter is opened in a new window.

Because the open method is available on the global window object, we can omit the .window reference in our code:

open("https://www.openjavascript.info") 
// Equivalent to window.open(" https://www.openjavascript.info")

Optional second parameter: opening behaviour

We can change this default behaviour by entering a second parameter:

Parameter valueOpens 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:

open("https://www.openjavascript.info", "_self"); 
// Opens URL in this window

If we are okay with the default behaviour of _blank, we can use the second parameter to enter a name for the new window.

const newWindow =  open("https://www.openjavascript.info", "openJavaScript"); 
// Opens URL in new window called "OpenJavaScript"

console.log(newWindow.name) 
// Returns: "openJavaScript"

Optional third parameter: dimension and screen placement

If we want to make specifications about the dimensions and screen placement of the new window, we enter this information as a third parameter:

Parameter valueSets:
width=pixelsWidth 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

All third parameter specifications must be placed inside the same double quotes, each separated by a comma:

open("http://www.google.com", "", "width=200, height=200,left=30,top=20");

Closing the window

If we have saved the new window in a variable, we can use the window.close() to close it:

const newWindow = open("https://www.openjavascript.info");

newWindow.close();

In the above example, the window is opened and then closed immediately afterwards so that there is no time to see its contents.

We can put a time delay on the execution of the close() method with setTimeout():

const newWindow = open("https://www.openjavascript.info");

setTimeout( () => { newWindow.close() }, 5000); 
// triggers the close method to run after 5 seconds

This allows us to see close() in action.