How to Close a Target Window in JavaScript Using window.close()
Learn how to properly close a target window in JavaScript using window.close(), with tips on handling child windows and browser restrictions.
132 views
To close a target window in JavaScript, use the `window.close()` method. However, this method only works for windows that were opened by JavaScript using the `window.open()` method. For security purposes, browsers restrict scripts from closing windows that weren't opened programmatically. To close a child window, store the window object in a variable when you open it (`let childWindow = window.open('url')`) and call `childWindow.close()` to close it. Remember, this action must be user-initiated, like within a click event handler, to work properly.
FAQs & Answers
- Can I close any browser window using JavaScript? No, JavaScript can only close windows that were opened programmatically using the window.open() method due to browser security restrictions.
- How do I close a child window in JavaScript? Store the child window object when you open it using let childWindow = window.open('url'), then call childWindow.close() to close it.
- Why does window.close() sometimes not work? window.close() often requires a user-initiated action like a click event and only works on windows opened via JavaScript to prevent abuse by malicious scripts.