Categories
JavaScript Answers

How to capture the close event of popup window in JavaScript?

Spread the love

Sometimes, we want to capture the close event of popup window in JavaScript.

In this article, we’ll look at how to capture the close event of popup window in JavaScript.

How to capture the close event of popup window in JavaScript?

To capture the close event of popup window in JavaScript, we can watch for the window to close with a timer.

For instance, we write

const win = window.open("https://www.example.com");

const timer = setInterval(() => {
  if (win.closed) {
    clearInterval(timer);
    console.log("closed");
  }
}, 1000);

to call window.open to open a popup with the URL.

Then we call setInterval with a callback that checks if the popup is closed with win.closed every second.

If it’s true, then we call clearInterval with timer to stop the setInterval timer.

Conclusion

To capture the close event of popup window in JavaScript, we can watch for the window to close with a timer.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *