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

We are going to be looking at the method to close the current tab in a browser window using JavaScript. Earlier it used to happen that with a simple JavaScript function, the current tab used to get closed. The following syntax was used for this purpose.

Syntax:

window.close()

But accounting for a security feature, which 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 to open GeekForGeeks window and then close it.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
  
<html>
<head>
    <style>
        body{
            text-align:center;
        }
    </style>
</head>
  
<body>
  
    <h2 style="color:green">GeeksforGeeks</h2>
    <h4 style="color:purple">Close Tab/Window using JavaScript</h4>
  
    <button onclick="openWin()">Click to open GeeksforGeeks website</button>
  
    <button onclick="closeWin()">Click here to close the window</button>
  
    <script>
        var myGeeksforGeeksWindow;
  
        function openWin() {
            myGeeksforGeeksWindow = window
                     .open("https://www.geeksforgeeks.org", "_blank", "width=786, height=786");
        }
  
        function closeWin() {
            myGeeksforGeeksWindow.close();
        }
    </script>
  
</body>
  
</html>

chevron_right


Output:
When we load the code:
ngcut

New Window/Tab gets opened up:
ngcut

The Window/Tab gets closed:
ngcut

The entire process:
ngcut



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.