How to Close a Window with a Button in JavaScript: Step-by-Step Guide
Learn how to close a browser window using a button in JavaScript with the window.close() method and important browser restrictions.
300 views
To close a window with a button in JavaScript, simply use the `window.close()` method. First, create the button in your HTML file. Then, add an `onclick` event to it like this: `<button onclick="window.close();">Close Window</button>`. It's important to note that this method will only work for windows that were opened by a script using the `window.open()` method, due to browser security restrictions.
FAQs & Answers
- Can I close any browser window using JavaScript? No, due to browser security restrictions, JavaScript's window.close() method only works on windows that were opened by the script using window.open().
- How do I create a button to close a window in JavaScript? Create an HTML button element and add an onclick event with window.close(), like <button onclick="window.close();">Close Window</button>.
- Why doesn't window.close() work on all windows? Most browsers block scripts from closing windows or tabs that were not opened via window.open() to prevent unwanted behaviors.