How to Detect if a JavaScript Window Open Is Closed?

Learn how to detect if a window opened via JavaScript is closed by monitoring the window.closed property with setInterval.

60 views

To detect if a window open is closed, monitor the `closed` property of the window object you've opened. This is done by first creating a variable to hold the new window reference, for example, `var myWindow = window.open(URL, name, specs);` Then, periodically check the `myWindow.closed` property using a function with `setInterval()`. If `myWindow.closed` is `true`, the window has been closed. This technique allows you to perform actions based on the window's open or closed status.

FAQs & Answers

  1. What does the window.closed property indicate in JavaScript? The window.closed property returns a boolean indicating whether the referenced window has been closed (true) or is still open (false).
  2. How can I check if a popup window is closed in JavaScript? You can store the window reference returned by window.open in a variable and periodically check the variable's closed property using setInterval to detect when the window closes.
  3. Why use setInterval to monitor window.closed status? Using setInterval allows your script to continuously check the window.closed property at regular intervals so you can respond immediately when the window closes.
  4. Can I perform actions after detecting a window is closed? Yes, once your script detects the window is closed, you can execute functions such as cleaning up resources, updating UI elements, or triggering other processes.