JavaScript allows you to close a browser window using the window.close()
method. This can be useful when you open a new window or tab using JavaScript and want to close it later — for example, after the user finishes a task or clicks a "Close" button.
In this article, you'll learn how window.close()
works, when it can be used, and why it sometimes doesn't work as expected.
What is window.close()
?
The window.close()
method is used to close the current browser window or tab. However, for security reasons, it only works on windows that were opened using JavaScript (like with window.open()
).
Syntax:
Example: Open and Then Close a Window
What it does:
This script opens a new small window, waits 3 seconds, and then automatically closes it.
Why window.close()
Might Not Work
-
Browser restrictions: Most browsers block scripts from closing a window unless that window was opened using JavaScript.
-
User-initiated action required: Some browsers allow closing only when triggered by a user click.
-
Can't close main tab: You cannot close the original tab/window the user opened your site in — for security reasons.
Example: User Click Closes a Window
Summary
The window.close()
method lets you close browser windows or tabs — but only those that were opened using JavaScript (like with window.open()
). You can't use it to close the original window your site loaded in, due to browser security rules.
Key Points:
-
Only works on JavaScript-opened windows
-
May not work if popup blockers are enabled
-
Must usually be triggered by a user action