How to close current window (tab) with jscript and HTML

window.close();

Modern browsers usually don’t allow this behavior and closing the current window or tab with jscript is doable only if you previously opened that window with jscript. However, searching for the solution about this topic I managed to make this work and here it is how.

You can learn about Window close() Method on-line and it is somewhat useful in some cases. My case was to close the window which opens in new tab after clicking on image file of a website.
I downloaded an image with an X in a red circle to stand for a closing button and positioned it in the upper right corner of the page. You might as well use the font for this purpose. In any case, here is how to close the current browser tab or window using HTML DOM.

1. The code for thesection of the page:

<script>
    function closeWindow() {
        window.open('','_parent','');
        window.close();
    }
</script>

2. The code for the section of the page where the closing button should appear (in my case at the start of the body tag):

<div style="position: absolute; right: 20px; top: 20px"><a href="javascript:closeWindow();"><img src="close-button.png" width="32" height="32"></a></div>

That’s it. You’re done. This works in Firefox, Chrome and MS Edge… at least for me 🙂

The trick about this code is that you first “tell” the browser that the current window is opened by jscript

window.open('','_parent','');

and then you initiate the closing with

window.close();

Please note that you can also split the styling part of the HTML code and insert it into the CSS file, but if you don’t have access to it then the in-line styling like this can also do the trick.

By janoshke

Web developer and IT consultant. Freelancer with full respect for OpenCart and WordPress. Gamer, (ex)drummer and parent.

2 comments

Leave a Reply