How to Close Browser Tab using JavaScript

← PrevNext →

You can use the window.close() method to close the current browser tab or window in JavaScript. However, this method should be used in conjunction with the window.open() method. The window.close() method will only close a tab or window that was opened by JavaScript.

Here’s an example.

<script>
    let openCloseTab = () => {
        let win = window.open('https://www.encodedna.com/', '_blank'); 
        win.close();       // Now, close the tab.
    }

    openCloseTab();
</script>
Try it

The .open() method opens the web page in a new tab, since the _blank option is used. The page immediately closes, as the .close() method is called right after the .open() method.

This can be a one-liner code.

const win = window.open('https://www.encodedna.com/', '_blank').close();

The above method opens and closes the new tab in a flash 💥. You can hardly see it happen, but it works.

There’s an alternative method.

<body>
    <p><input type='button' id='bt1' onclick='openNewTab()' value='Open New Tab'></p>
    <input type='button' id='bt3' onclick='closeTab()' value='Close the Tab'>
</body>

<script>
    let win;
    let openNewTab = () => {
       win = window.open('https://www.encodedna.com/', '_blank'); 
    }

    let closeTab = () => {
       win.close();
    }
</script>
Try it

In this example, the first function opens a new tab and the second function closes the same tab. The variable win keeps track of which window to close.

This Code works in Internet Explorer

Note: To make the above example work in "Internet Explorer', use the following code instead. I ran this code in IE 10 and 11.

<body>
    <input type='button' id='bt1' onclick='openNewTab()' value='Open New Tab'>
    <br />
    <input type='button' id='bt3' onclick='closeTab()' value='Close the Tab'>
</body>

<script>
    // This script will work in Internet Explorer.
    var win;
    function openNewTab() {
        win = window.open('https://www.encodedna.com/', '_blank');
    }

    function closeTab() {
        win.close();
    }
</script>

Oh, why use buttons, when you can use a Timer to Close automatically

Here’s how you can do this.

<script>
    let win;
    let openNewTab = () => {
        win = window.open('https://www.encodedna.com/', '_blank'); 
    }
    
    let closeTab = () => {
   	    win.close();
    }
    setTimeout(closeTab, 2000);   // Close the tab after 2000 miliseconds or 2 seconds.

    // For more on setTimeout() function read this article here… https://www.encodedna.com/javascript/redirect-page-after-a-delay-using-javascript.htm 
    
    openNewTab();
</script>
Try it

There are so many ways you can close a browser tab using JavaScript. However, remember the tabs that you want the script to close, should have been opened by the script itself.

← PreviousNext →