How to Capture Popup Window Close Event in JavaScript

In this tutorial, we’ll show you how to capture the popup window close event in JavaScript using the onbeforeunload event handler. This technique can be useful for tracking user behavior or performing specific actions when a user closes a popup window. Let’s get started!

To capture the popup window close event in JavaScript, you can use the following code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Open the popup window
var popup = window.open("popup.html", "Popup", "width=400,height=400");
// Attach the onbeforeunload event handler to the popup window
popup.onbeforeunload = function() {
// This code will be executed when the popup window is closed
alert("Popup window closed!");
};
// Open the popup window var popup = window.open("popup.html", "Popup", "width=400,height=400"); // Attach the onbeforeunload event handler to the popup window popup.onbeforeunload = function() { // This code will be executed when the popup window is closed alert("Popup window closed!"); };
// Open the popup window
var popup = window.open("popup.html", "Popup", "width=400,height=400");

// Attach the onbeforeunload event handler to the popup window
popup.onbeforeunload = function() {
    // This code will be executed when the popup window is closed
    alert("Popup window closed!");
};

In the example above, we first open the popup window using the window.open() method. We then attach the onbeforeunload event handler to the popup window, which will be triggered just before the popup window is closed. Inside the event handler function, we can add the code that we want to execute when the popup window is closed, in this case, an alert message.

Using this technique, you can track user behavior or perform other actions when a user closes a popup window.

Capturing the popup window close event in JavaScript is a useful technique for tracking user behavior or performing specific actions when a user closes a popup window. By using the onbeforeunload event handler, you can execute custom code just before the popup window is closed.