How to open and close a new browser window using JavaScript?

October 21, 2020 - 2 min read

Open a window

To open a new window using JavaScript, you can use the open() method in the global window object.

// open a new window
// with google.com as the url
window.open("https://google.com");

The window.open() method accepts 1 required and 2 optional arguments:

  • it accepts a valid URL of the string type as the first argument (Required).
  • A window name of string type as the second argument (Optional).
  • Window features of string type as the third argument (Optional).

If the method executes and a window is opened it will return an object with the method and properties of the newly opened window.

If the method didn't execute properly, it will return null.

Specify the features for the new window

The window feature is separated by comma , in a string and should be supplied as the third argument to the window.open() method.

You can specify the feature for the new window like:

  • To set the size of the new window as width and height
  • Whether to show menubar or not using menubar
  • Whether to show toolbar (back, forward, button, etc.) or not
  • Whether to make the new window resizable
  • Whether it should have scroll bars or not

For example, let's make a new window which opens google.com with some window features like the,

  • width to be 800
  • height to be 600
  • let's make it resizable
  • and to show scrollbars.

This can be done like this,

// open a new window
// with google.com as the url
const openedWindow = window.open(
  "https://google.com",
  "Google Search",
  "width=800,height=600,resizable,scrollbars"
);

Close an opened window

To close an opened window, you can use the close() method on the object returned from the open() method.

// open a new window
// with google.com as the url
const openedWindow = window.open(
  "https://google.com",
  "Google Search",
  "width=800,height=600,resizable,scrollbars"
);

// close the opened window
openedWindow.close();

NOTE: The window.open() method may be blocked by some modern browsers if it invoked automatically by the JavaScript. It is better to use this method inside a click event handler or something like that.

See this example live in JSBin.

Feel free to share if you found this useful 😃.