0

As many resources state, e.g. this SO post: javascript close current window as well as Mozilla's own documentation, it shouldn't be possible to close a window/new tab that wasn't opened by javascript through window.open().

However, I've just experienced that this works perfectly when then new tab has been opened through an anchor tag with the attribute target="_blank" in all the mentioned browsers at the bottom - however, it didn't work in Mozilla Firefox when the rel="noopener" attribute were included (did work without, but as per Mozilla's documentation, don't leave it out for security reasons).

How come this is the case? Is the target="_blank" simply considered a script?

Below you can find 2 sample codes that you can copy/paste into HTML files and try out on your own computer.

First file: open the new tab:

<html>
<body>
<a href="C:\Users\..{insert your own file path here to the sample code below}" target="_blank" rel="noopener noreferrer">Open new tab</a>
</body>
</html>

Second file: the HTML that you open with above snippet - contains a button to close same tab:

<html>
<body>
<button onclick="window.close();">Close me!</button>
</body>
</html>

This has also been tested on a live website and has been tested to work on the following browsers as well:

  • Internet Explorer, version 11.1397.17763.0 (with "blocked script/activeX content" allowed)
  • Chrome, version 85.0.4183.83
  • Edge, version 85.0.564.44

As mentioned above, it didn't work in Mozilla Firefox when rel="noopener" was included.

Chri.s
  • 1,386
  • 1
  • 12
  • 23

1 Answers1

4

How come this is the case? Is the target="_blank" simply considered a script?

The MDN already links to the relevant specifications.

https://html.spec.whatwg.org/multipage/window-object.html#dom-window-close says the window can be closed, if it is script-closable, and links to the following definition of that,

A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a top-level browsing context whose session history contains only one Document.

(https://html.spec.whatwg.org/multipage/window-object.html#script-closable)

target="_blank" creates a top-level browing context, and as long as you don’t navigate anywhere inside the popup, it also has a one-document history … So it is allowed to be closed by script.

CBroe
  • 91,630
  • 14
  • 92
  • 150