Sometimes, we want to open a popup with JavaScript and then detect when the user closes it.
In this article, we’ll look at how to open a popup with JavaScript and then detect when the user closes it.
How to open a popup with JavaScript and then detect when the user closes it?
To open a popup with JavaScript and then detect when the user closes it, we can use the closed
property.
For instance, we write
const winObj = window.open(
"http://www.eexample.com",
"google",
"width=800,height=600,status=0,toolbar=0"
);
const loop = setInterval(() => {
if (winObj.closed) {
clearInterval(loop);
alert("closed");
}
}, 1000);
to call window.open
to open a popup window.
Then we call setInterval
with a callback that checks if winObj.closed
is true
.
If it is, then we call clearInterval
to stop running the setInterval
callback every second and call alert
to show an alert box.
Conclusion
To open a popup with JavaScript and then detect when the user closes it, we can use the closed
property.