How to Close a Window Opened by JavaScript Using window.close()

Learn how to properly close a browser window opened via JavaScript using window.close() and understand browser restrictions on this method.

104 views

To close a window opened via JavaScript, use the `window.close()` method. However, this method only works for windows that were opened using JavaScript's `window.open()` method. Note: Most modern browsers restrict this behavior to avoid unwanted pop-ups and only allow it if the script attempting to close the window is running in the context of the window it's trying to close.

FAQs & Answers

  1. Can I use window.close() to close any browser window? No, window.close() only works to close windows that were opened by JavaScript using window.open(). Most modern browsers restrict closing windows not opened by scripts to prevent abuse.
  2. Why does window.close() sometimes not work in modern browsers? Modern browsers limit the use of window.close() to scripts running in the same window context originally opened by JavaScript, to avoid unexpected or unwanted pop-ups from being closed.
  3. How do I open and close a new window in JavaScript correctly? Use window.open() to open a new window, which returns a reference to that window, and then call window.close() on that reference to close it safely within browser restrictions.