JavaScript

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

In this tutorial, we are going to see how to close the current tab in a browser window with JavaScript. There is a method in JavaScript available that allows you to close the tab for the current window. This, is the close() method:

window.close()

You should know that window.close() method can only close the tab opened using window.open() method. So, to close the current tab in javaScript, it must be opened using the window.open() method.
 

 

Example:
<!DOCTYPE html> 
<html> 
<head></head> 
<body>   
    <button onclick="openW()">Click to open StackHowTo website</button> 
    <button onclick="closeW()">Click here to close the window</button> 
    <script> 
      var win; 
      function openW() { 
        win = window.open("https://stackhowto.com", "_blank", "width=900, height=786"); 
      }
      function closeW() { 
        win.close(); 
      }
    </script> 
</body> 
</html>
Result
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *