window.close() method

To make this, we will use window.close() method.  This method is used to close the window which is opened by the window.open() method

Syntax:

window.close();

But accounting for a security feature, that was introduced a few years ago, ordinary JavaScript lost its privilege to close the current tab, just by using this syntax. 

Note: A current window/tab will only get closed if and only if it was created & opened by that script. Means the window.close syntax is only allowed for the window/tab that is created & opened using window.open method

Example: This example shows how to open the w3wiki window and then close it. 

html




<!DOCTYPE html>
<html lang="en">
 
<head>
    <title>
        How to close current tab in a
        browser window using JavaScript?
    </title>
</head>
 
<body style="text-align: center;">
    <h2 style="color:green;">
        w3wiki
    </h2>
     
    <h4 style="color:purple">
        Close Tab/Window using JavaScript
    </h4>
 
    <button onclick="openWin()">
        Click to open w3wiki website
    </button>
 
    <button onclick="closeWin()">
        Click here to close the window
    </button>
 
    <script>
        let myw3wikiWindow;
 
        function openWin() {
            myw3wikiWindow = window
                .open("https://www.w3wiki.org",
                "_blank", "width=786, height=786");
        }
 
        function closeWin() {
            myw3wikiWindow.close();
        }
    </script>
</body>
 
</html>


Output:  

Output



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

In this article, we will see how to close the current tab in a browser window using JavaScript.

Similar Reads

window.close() method

To make this, we will use window.close() method.  This method is used to close the window which is opened by the window.open() method....