How to close current tab in a browser window using JavaScript?

In this post, we are going to look at the method to close the current tab of the browser window using JavaScript. In earlier time it was possible to close the current tab by using the window.close() function. The following syntax was used at that time:

Syntax:

window.close();

But as per the security feature, this syntax has lost its privilege to close the current tab. So you can not simply use the window.close() anymore to close the current tab of the browser.

A current tab or window can only be closed if it was created by that script. That means the window.close() function is only allowed for the window or tab that has been created and opened using the window.open() method.

See below example for the implementation:

<button>Click to open the window</button>
<button>Click here to close the window</button>
let myWindow;

function openMyWindow() {
    if(myWindow) // this will kill the window incase you click multiple times
    closeMyWindow();
    myWindow = window.open("http://www.ci3school.com", "_blank", "width=786, height=786");
}

function closeMyWindow() {
    myWindow.close();
}

So this is how you can easily close the current tab in a browser window using JavaScript.

Leave a Reply