docs.rodeo

MDN Web Docs mirror

Window: open() method

{{APIRef}} 

The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an iframe) under a specified name.

Syntax

open()
open(url)
open(url, target)
open(url, target, windowFeatures)

Parameters

[!NOTE] Requested position (top, left), and requested dimension (width, height) values in windowFeatures will be corrected if any of such requested value does not allow the entire browser popup to be rendered within the work area for applications of the user’s operating system. In other words, no part of the new popup can be initially positioned offscreen.

Return value

If the browser successfully opens the new browsing context, a WindowProxy object is returned. The returned reference can be used to access properties and methods of the new context as long as it complies with the same-origin policy security requirements.

If the {{httpheader("Cross-Origin-Opener-Policy")}}  HTTP header is being used, and the document policies are such that the document is opened in a new {{glossary("Browsing context","browsing context group")}} , references to the opened window are severed and the returned object will indicate that the opened window is closed ({{domxref("Window.closed","closed")}}  is true).

null is returned if the browser fails to open the new browsing context, for example because it was blocked by a browser popup blocker.

Description

The Window interface’s open() method takes a URL as a parameter, and loads the resource it identifies into a new or existing tab or window. The target parameter determines which window or tab to load the resource into, and the windowFeatures parameter can be used to control to open a new popup with minimal UI features and control its size and position.

Remote URLs won’t load immediately. When window.open() returns, the window always contains about:blank. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.

Modern browsers have strict popup blocker policies. Popup windows must be opened in direct response to user input, and a separate user gesture event is required for each Window.open() call. This prevents sites from spamming users with lots of windows. However, this poses an issue for multi-window applications. To work around this limitation, you can design your applications to:

Examples

Opening a new tab

window.open("https://www.mozilla.org/", "mozillaTab");

Opening a popup

Alternatively, the following example demonstrates how to open a popup, using the popup feature.

window.open("https://www.mozilla.org/", "mozillaWindow", "popup");

It is possible to control the size and position of the new popup:

const windowFeatures = "left=100,top=100,width=320,height=320";
const handle = window.open(
  "https://www.mozilla.org/",
  "mozillaWindow",
  windowFeatures,
);
if (!handle) {
  // The window wasn't allowed to open
  // This is likely caused by built-in popup blockers.
  // …
}

Progressive enhancement

In some cases, JavaScript is disabled or unavailable and window.open() will not work. Instead of solely relying on the presence of this feature, we can provide an alternative solution so that the site or application still functions.

Provide alternative ways when JavaScript is disabled

If JavaScript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the target attribute. The goal and the idea are to provide (and not impose) to the user a way to open the referenced resource.

HTML

<a href="https://www.wikipedia.org/" target="OpenWikipediaWindow">
  Wikipedia, a free encyclopedia (opens in another, possibly already existing,
  tab)
</a>

JavaScript

let windowObjectReference = null; // global variable
function openRequestedTab(url, windowName) {
  if (windowObjectReference === null || windowObjectReference.closed) {
    windowObjectReference = window.open(url, windowName);
  } else {
    windowObjectReference.focus();
  }
}

const link = document.querySelector("a[target='OpenWikipediaWindow']");
link.addEventListener(
  "click",
  (event) => {
    openRequestedTab(link.href);
    event.preventDefault();
  },
  false,
);

The above code solves a few usability problems related to links opening popups. The purpose of the event.preventDefault() in the code is to cancel the default action of the link: if the event listener for click is executed, then there is no need to execute the default action of the link. But if JavaScript support is disabled or non-existent on the user’s browser, then the event listener for click is ignored, and the browser loads the referenced resource in the target frame or window that has the name "WikipediaWindowName". If no frame nor window has the name "WikipediaWindowName", then the browser will create a new window and name it "WikipediaWindowName".

[!NOTE] For more details about the target attribute, see <a> or <form>.

Reuse existing windows and avoid target="_blank"

Using "_blank" as the target attribute value will create several new and unnamed windows on the user’s desktop that cannot be recycled or reused. Try to provide a meaningful name to your target attribute and reuse such target attribute on your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single target attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window, which is recycled.

Here is an example where a secondary window can be opened and reused for other links:

HTML

<p>
  <a href="https://www.wikipedia.org/" target="SingleSecondaryWindowName">
    Wikipedia, a free encyclopedia (opens in another, possibly already existing,
    tab)
  </a>
</p>
<p>
  <a
    href="https://support.mozilla.org/products/firefox"
    target="SingleSecondaryWindowName">
    Firefox FAQ (opens in another, possibly already existing, tab)
  </a>
</p>

JavaScript

let windowObjectReference = null; // global variable
let previousURL; /* global variable that will store the
                    url currently in the secondary window */
function openRequestedSingleTab(url) {
  if (windowObjectReference === null || windowObjectReference.closed) {
    windowObjectReference = window.open(url, "SingleSecondaryWindowName");
  } else if (previousURL !== url) {
    windowObjectReference = window.open(url, "SingleSecondaryWindowName");
    /* if the resource to load is different,
       then we load it in the already opened secondary window and then
       we bring such window back on top/in front of its parent window. */
    windowObjectReference.focus();
  } else {
    windowObjectReference.focus();
  }
  previousURL = url;
  /* explanation: we store the current url in order to compare url
     in the event of another call of this function. */
}

const links = document.querySelectorAll(
  "a[target='SingleSecondaryWindowName']",
);
for (const link of links) {
  link.addEventListener(
    "click",
    (event) => {
      openRequestedSingleTab(link.href);
      event.preventDefault();
    },
    false,
  );
}

Same-origin policy

If the newly opened browsing context does not share the same origin, the opening script will not be able to interact (reading or writing) with the browsing context’s content.

// Script from example.com
const otherOriginContext = window.open("https://example.org");
// example.com and example.org are not the same origin

console.log(otherOriginContext.origin);
// DOMException: Permission denied to access property "origin" on cross-origin object
// Script from example.com
const sameOriginContext = window.open("https://example.com");
// This time, the new browsing context has the same origin

console.log(sameOriginContext.origin);
// https://example.com

For more information, refer to the Same-origin policy article.

Accessibility concerns

Avoid resorting to window.open()

It is preferable to avoid resorting to window.open(), for several reasons:

Never use window.open() inline in HTML

Avoid <a href="#" onclick="window.open(…);"> or <a href="javascript:window\.open(…)" …>.

These bogus href values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.

If necessary, use a <button> element instead. In general, you should only use a link for navigation to a real URL.

Identify links that will open new windows in a way that helps navigation for users.

<a target="WikipediaWindow" href="https://www.wikipedia.org">
  Wikipedia (opens in new tab)
</a>

The purpose is to warn users of context changes to minimize confusion on the user’s part: changing the current window or popping up new windows can be very disorienting to users (in the case of a popup, no toolbar provides a “Previous” button to get back to the previous window).

When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in “background” or not).

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN