How to Close Current Window and Open a New Window in JavaScript
Learn how to close the current browser window and open a new one using JavaScript with practical examples and browser restrictions explained.
240 views
To close the current window and open a new one using JavaScript, use the `window.close()` method to close the current window. Then, use `window.open(url)` to open a new window. For example: `window.close(); window.open('https://www.example.com');`. Note that modern browsers may restrict these actions to user-initiated events to prevent pop-up spamming.
FAQs & Answers
- Can I close the current browser window using JavaScript? Yes, you can close the current window using the window.close() method, but modern browsers often restrict this action unless it is triggered by a user-initiated event.
- How do I open a new window in JavaScript after closing the current one? First, call window.close() to close the current window, then use window.open('your-url') to open a new window. Note that these should often be done in response to user actions.
- Why does window.close() sometimes not work in my browser? Most modern browsers block window.close() commands if they are not initiated by user actions like clicks, to prevent unwanted pop-ups.