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.