Search code examples
javascript

Execute a function after popup window is closed


I have a popup window that I create as follows:

popupWindow = window.open("about:blank", "_blank", "popup=yes");

And I have a function afterFn() that I need to execute after the popupWindow is closed.

My current approach is as follows:

async function pollPopupWindow() {
  while (popupWindow) {
    await new Promise((r) => setTimeout(r, 1000));
    if (popupWindow.closed) {
      popupWindow = null;
      afterFn();
    }
  }
}
pollPopupWindow();

I was wondering if it's possible to simply execute the afterFn() at the popup window closing time? I tried the following code but it did not work

popupWindow.addEventListener("beforeunload", () => {
  afterFn();
});

any ideas?


Solution

  • Your approach with addEventListener('beforeunload') won't work because the beforeunload event isn't triggered when a popup window is closed, but rather when a page inside the popup is unloaded (e.g., the user navigates away or reloads the popup). So all in all, it's just a matter of your desired functionality and it seems like your current approach is the best one.