Closing a Browser Window with JavaScript
Overview
Sometimes it is needed to close a browser window that we opened, we can do this using javascript but due to security reasons, we can close only those browser windows that we opened using javascript script and not the windows that are opened by the user.
Introduction
The only thing to be noted here is that we can close only those browser windows that we opened using our javascript script/code. Today's security standards do not allow closing the browser windows (using javascript script) that are opened by the user.
The below steps demonstrate the approach in which we open a URL using javascript so that it can be closed using the script :
-
Opening a new browser window using the javascript open method: First, it is needed to open a new browser window using the window.open() method. It takes two arguments, the first argument is the current URL which we will access through the location property of the window object and the second argument is the target URL which we will pass as _self because it makes the URL replace the current page.
-
Closing this opened window using the javascript close method: Since we opened the new browser window using the javascript script therefore we can close it using the window.close() method. This method does not any argument and it closes the window on which it is called.
JavaScript Program to Close a Browser Window Using window.close() Method
The below program demonstrates the approach we discussed above.
Output:
- Before clicking the close button browser window looks like the below.
-
After clicking the close button, the above page closes.
Explanation: First, we created an HTML document and under the body tag, we defined an h1 heading tag that displays Hello World!! and also we have defined a paragraph tag that says to click the button to close the window. Then we have defined the button and attached on click listener to it which defines what happens when the button is clicked. At last, we have the javascript script which defines the functionality of the above-defined function. The script contains a function in which we have defined a variable my_window and opened the new window, then we closed the current window using the close() method.
Conclusion
- To close a browser window we can use the javascript close method but we can use this method only when we have opened a new browser window using code.
- Due to modern security reasons, we cannot close a browser window that is opened by the user.
- To Open a new browser window we use the javascript open() method.
- To close this browser window we use the javascript close method.