How to Close Browser Tab using JavaScript

← PrevNext →

You can use window.close() method to close the current browser tab/window in JavaScript. However, the method should be used with window.open() method. The ".close()" method will close a tab or window which is 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 I have used the "_blank" option. The page immediately closes, since the .close() method is called right after the ".open()" method.

This can be a one-liner code. For example,

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 worked.

There’s another method however.

<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

Now you can see what the code executes and how it executes. The first function opens a new tab and the second function closes the same tab. The variable win knows which window to close.

This Code works in Internet Explorer

Note: To make the above example work in "Internet Explorer', use the below code instead (using regular JS functions). 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 →