The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,860 other subscribers

javascript – Open a URL in a new tab (and not a new window) – Stack Overflow

Posted by jpluimers on 2025/01/28

TL;DR: you can force opening a new Window over a new Tab, but not the other way around.

Background information: [Wayback/Archive] javascript – Open a URL in a new tab (and not a new window) – Stack Overflow.

I learned that you can focus a new opened tab/window:

This is a trick,

window.open(url, '_blank').focus();

And that you cannot force opening a tab:

Nothing an author can do can choose to open in a new tab instead of a new window; it is a user preference. (Note that the default user preference in most browsers is for new tabs, so a trivial test on a browser where that preference hasn’t been changed will not demonstrate this.)

CSS3 proposed target-new, but the specification was abandoned.

The reverse is not true; by specifying certain window features for the window in the third argument of window.open(), you can trigger a new window when the preference is for tabs.

This forces opening a new Window as per [Wayback/Archive] javascript – HTML open fresh new window again on image onclick – Stack Overflow:

To trigger a new window instead of a new tab (something you should generally be reluctant to do) you need to specify some window features which the browser won’t apply to a tab.

Setting resizable is sufficient in Chrome. I haven’t tested in other browsers.

HTML:

<a href="http://placekitten.com/100/100" target="_blank">
  <img src="http://placekitten.com/100/100">
</a>

JS:

const openInNewWindow = event => {
  event.preventDefault();
  const {href, target} = event.currentTarget;
  const features = "resizable";
  window.open(href, target, features);
};


document.querySelector("a")
  .addEventListener("click", openInNewWindow);

(Don’t bind click event listeners to images, they aren’t designed as interactive controls. Users who depend on (for example) a screen reader or a keyboard focus to interact with a document will find it difficult or impossible to trigger a click on an image. Use semantic markup. If you are linking something, use a link, then enhance with JS.)

Thanks go to these StackOverflow users:

Background reading:

–jeroen

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.