What is the window.open() method in JavaScript?
If you wish to send a user to another webpage in HTML, you need to add that page’s url to the html anchor tag <a> href attribute. You also need to add the target if you want that link to be opened in a new browser window.
In JavaScript, you can do the same thing using the window.open() method.
The JavaScript option is useful, even though we can achieve this task with HTML as well. Sometimes, for example, we may need to redirect to a page in our JavaScript code.
JavaScript Windows.open
This class is used to open a new browser window.
The general syntax is described below.
Syntax
Window.open(URL,name,spec)
Parameter
All parameters of this method are optional. If none is specified, the method will open a new blank browser window.
-
URL: The URL parameter specifies the URL that will be opened in the new window. If no URL is indicated, a blank browser window will be opened. -
name: The name parameter is like thetargetattribute. It will specify if you want the new window to be one of the following:- A new blank one:
_blankwill be used. - To be loaded into the parent frame use
_parent. - Replace the current page use
_self. - Others like
_topand thenamewhich you will give the page in case you need to access it.
- A new blank one:
-
Specs: You can specify other edits you wish to give to this new window, like its mode, size, if it can be resized, toolbar and menu bar edits, etc.
Another parameter not listed is the
replaceparameter. This parameter is not supported any longer by browsers.
The options provided by this method might act differently on different browsers.
Code
In the code below we can see the window.open method used in various ways.
//no parameter to the method, no problems still worksvar firstWindow = window.open();//gives size to the new window with no url specifiedvar secondWindow = window.open("", "", "width=200,height=100");//this specified the name parameter as wellvar thirdWindow = window.open("", "NEWWindow", "width=200,height=100");// All parameter are specified over herevar fourthWindow = window.open("https://www.wikipedia.org", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");// using the document.write method to write to the new windowfirstWindow.document.write("<p>This is 'firstwindow'. I am 200px wide and 100px tall!</p>");