JavaScript Window close method
JavaScript provides an in-built function named close() to close the browser window that is opened by using window.open() method. Unlike the window.open() method, it does not contain any parameter. This window.close() method simply close the window or tab opened by the window.open() method.
Remember that – You have to define a global JavaScript variable to hold the value returned by window.open() method, which will be used later by the close() method to close that opened window.
Syntax
Here, window is the name of that window that is opened by the window open method.
Parameters List
This method does not have any parameters.
Close the window
Let’s understand with the help of an example. We will take an example to show you how to close the window or tab opened by the window.open() method.
Firstly, we will open a website URL in a new window (size defined in code) using a button click and then use another button to close that opened window.
Example
In this example, we will not specify any URL in open() method. See the below code how it will work:
Copy Code
Output
You will get the output same as the given below. Here, clicks the Open New Window button to open a user-defined browser window.
A new window will pop-up with a message, as shown below. Now, click the Close New Window button to close this pop-up window.
Example 2
This example will have a website URL inside the window.open() method to open a website in a new window. Then we will use close() method to close that window.
Copy Code
Output
When you will execute the code, you will get the response as shown below:
Click the Open tutoraspire button to open the tutoraspire tutorial website. We have specified the size (height and width) of the new pop-up window to open.
If you click the Close tutoraspire button, this opened window will be minimized.
Browser Support
Several web browsers support this window function, such as:
- Chrome
- Mozilla Firefox
- Internet Explorer (IE)
- Opera
- Safari, etc.
You can run window.close() JavaScript function on these above browsers.