JavaScript

How to Close Window Using JavaScript Which is Opened by the User With a URL?

JavaScript provides a variety of methods to perform any operation on a web page effectively. The window.open() method is used to open a tab in the browser. Moreover, the window.close() method can be employed to close the window utilizing JavaScript. That window is already opened by the user in the URL.

This post demonstrates the working and usage of the window.close() method to close the window with JavaScript that is already opened by a URL.

How to Use the window.close() Method in JavaScript?

In JavaScript, the window.close() method is utilized for closing the window that has already been opened by the window.open() method. The working of the window.close() method is described using the following syntax:

Syntax

window.close()

The window.close() method does not take any parameter, it just closes the existing open tab in the browser.

Note: Some of the browsers do not support the window.close() method if the window.open() method is not employed first to open any webpage.

For a better understanding, the following lines of code are implemented to close windows with the built-in methods of JavaScript.

Code

<html>

<head>

<center><h2 style="color:red"> An example of Window close() method </h2>

<body>

<b> Press the button to open Linuxhint site </b><br>

<button onclick="windowOpen()"> Open Linuxhint </button>

<br><br>

<b> Press the button to close Linuxhint site </b><br>

<button onclick="windowClose()"> Close Linuxhint </button>

</body> </center>

<script>

var newWindow;

function windowOpen() {

newWindow = window.open(

"https://linuxhint.com/declare-variables-different-ways-javascript/",

"_blank", "width=400, height=250"); }

function windowClose() {

newWindow.close(); }

</script> </head> </html>

In the above code:

  • two buttons Open Linuxhint and Close Linuxhint are created.
  • These buttons are associated with the windowOpen() and windowClose() methods to open and close the window tab.
  • URL is provided in the code to access a webpage.

Output

The output shows the execution of the window.close() method in JavaScript. The link is opened using the “Open Linuxhint” button. When the “Close Linuxhint” button is pressed, the window is closed.

Conclusion

The window.close() method can be used to close a window by utilizing JavaScript that is already opened by a URL. Most of the time, the window.close() method works with the window.open() method. For a better understanding, we have provided a detailed working and usage of the window.close() method alongside. In the provided example, the window is opened first, and then it is closed using the window.close() method in JavaScript.

About the author

Syed Minhal Abbas

I hold a master's degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.