How to Close a Window on Button Click Using JavaScript
Learn how to close a browser window with a button click in JavaScript using the window.close() method and event listeners.
114 views
To close a window on button click in JavaScript, use the `window.close()` method. First, ensure your script is running within the same window you wish to close. Then, attach an event listener to the button, invoking `window.close()` when clicked. Example: `document.getElementById('yourButtonId').addEventListener('click', function() { window.close(); });` Remember, for security reasons, modern browsers restrict this action to windows that were opened by a script.
FAQs & Answers
- Can window.close() be used to close any browser window? No, modern browsers allow window.close() to close only windows that were opened by a script, for security reasons.
- How do I attach a button click event to close the window in JavaScript? Use an event listener on the button element that calls window.close(), for example: document.getElementById('buttonId').addEventListener('click', function() { window.close(); });
- Why doesn't window.close() work on some browser tabs? window.close() does not work on tabs or windows not opened by script because browsers block scripts from closing tabs that the user opened manually.