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.
Windows.open
This class is used to open a new browser window.
The general syntax is described below.
Window.open(URL,name,spec)
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 the target
attribute. It will specify if you want the new window to be one of the following:
_blank
will be used._parent
._self
._top
and the name
which you will give the page in case you need to access it.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
replace
parameter. This parameter is not supported any longer by browsers.
The options provided by this method might act differently on different browsers.
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>");