How to Close a Window Popup in JavaScript: Step-by-Step Guide
Learn how to properly close window popups in JavaScript using window.open() and window.close() with browser restrictions in mind.
152 views
To close a window popup in JavaScript, first ensure you have a reference to the window you opened. If you opened the window using `window.open()`, store the returned value in a variable. For example, `let myWindow = window.open('https://example.com');`. When you need to close this window, call `myWindow.close();`. If you're trying to close the current window, use `window.close();` directly. Note that modern browsers restrict the use of `window.close()` to windows that were opened by a script, to prevent malicious websites from closing browser windows unexpectedly.
FAQs & Answers
- Can I close any browser window using JavaScript? No, modern browsers only allow scripts to close windows that were opened by that script to prevent misuse, so you cannot close arbitrary browser windows with JavaScript.
- How do I get a reference to a popup window in JavaScript? You can get a reference by storing the returned value from window.open(), like let myWindow = window.open('url');, which you can later use to close the window.
- What happens if I call window.close() on the current browser tab? Calling window.close() on the current tab will only work if the tab was opened by a script; otherwise, modern browsers block this action for security reasons.