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?