JavaScript: Open URL

By Xah Lee. Date: . Last updated: .

The window.open() method lets you open a new URL. Example:

Click Me to open JavaScript In Depth

Here is the code.

<p>
<span id="clickOpen62488">Click Me</span>
to open JavaScript In Depth
</p>
const clickOpen62488 = document.getElementById("clickOpen62488");

const openIt = (() => { open( "http://xahlee.info/js/js.html", "_blank"); });

clickOpen62488. addEventListener( "click", openIt, false);

window.open Parameters

window.open(url, windowName, windowFeatures, replaceCurrent).

The url is a URL to open. Can be empty string.

All other parameters are optional.

The windowName 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. See:

windowFeatures is spec for window parameters. Example: "width=640,height=480,menubar=no,scrollbar=no". It specifies window size, position, show scrollbar, toolbar, url field, etc.

Here is a example using the parameter:

const popup = (() => {
  open(
    "http://xahlee.info/js/js.html",
    "_blank",
    "width=640,height=480,menubar=no,scrollbar=no",
  );
});

document.getElementById("clickBox85509").addEventListener(
  "click",
  popup,
  false,
);

click me to see popup window.

replaceCurrent is true or false. If true, replace the current URL in history list.

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.

BUY ΣJS JavaScript in Depth