Javascript open new tab, and wait for it to close

You can open a new page using window.open() and then check periodically to see if the window has been closed. The reference to the opened window is returned by window.open() and you can check if it has been closed using windowHandle.closed.

btn.onclick = () => {
  const win = window.open(
      'https://www.stackoverflow.com/',
      'Secure Payment');
  const timer = setInterval(() => {
    if (win.closed) {
      clearInterval(timer);
      alert('"Secure Payment" window closed!');
    }
  }, 500);
}

See, also, this short demo.

For more info on window.open() and best practices, take a look at MDN.


Before closing the popup, try opener.someFunction() to call a function in the window that opened it. Note that this will fail if the user closed the first window, or if the user navigated it to another site, or if the two windows are on different domains for whatever reason.


The best approach with data transfer from the child window I found.

Parent code

window.open(url);
await new Promise(resolve => window.addEventListener('custom', resolve));

Child code

if(window.opener) {
  const customEvent = new CustomEvent('custom', { detail: {} });
  window.opener.dispatchEvent(customEvent);
  window.close();
}

Tags:

Javascript