JS: Open URL window.open(…)
The window.open()
method lets you open a new URL. Example:
click me to visit my JavaScript tutorial
Here's the code.
<p id="open42311">click me to visit my JavaScript tutorial</p>
function openIt () { open( "http://xahlee.info/js/js.html", "_blank"); } document.getElementById("open42311").addEventListener( "click", openIt, false);
The window.open()
property can be written just as open()
.
[see JS: Browser Window Object, Document Object Model]
For how event works, see: DOM: Add/Remove Event Handler
window.open() Parameters
window.open()
accepts 4 parameters, all optional. Only the first one is really necessary.
- URL (string)
- a window name (string).
- spec for window parameters. (string) Such as window size, position, show scrollbar, toolbar, etc.
true
orfalse
. Iftrue
, whether to replace the current URL in history list.
The window name is a string, and some value has special meaning:
name
→ a name of the window. name can be arbitrary. If that named window already exist, open in that window, else new window/tab._blank
→ open in new window (or tab). This is default_parent
→ open in parent frame._self
→ open in current window._top
→ open and replace framesets.
The “window name” concept and their special names is from old HTML spec (1990s), where a anchor <a>
can have a name
attribute. This “name” attribute is also used by frames:
Window Parameter Spec (size, position, toolbars)
The 3rd parameter to window.open()
is a string. The purpose is to specify the newly opened window's position, size, whether to show toolbars, url field, etc. It is rarely used today. Most browsers will block popup anyway. There are many implicit restrictions by different browsers because spammer abused this feature to make it looks identical to a system alert (such as out of memory), and trick people to click, resulting visiting ad sites or malware sites.
Here's a example using the parameter:
function popup () { open( "http://xahlee.info/js/js.html", "_blank", "width=640,height=480,menubar=no,scrollbar=no"); } document.getElementById("popup44429"). addEventListener( "click", popup, false);
click me to see
For a complete list, see: https://developer.mozilla.org/en-US/docs/Web/API/Window.open
window.open() Return Value
window.open()
return a new window
object.
Patreon me $5. Ask me question on patreon