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
stringtype as the first argument (Required). - A window name of
stringtype as the second argument (Optional). - Window features of
stringtype 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
widthandheight - 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,
widthto be800heightto be600- 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.