how to check if a tab opened using window.open() is still running or shut or refreshed?

 const newWindow = window.open(
      "",
      "_blank",
      "width=800,height=600,left=2000,top=0"
    );

    if (newWindow) {
      const specificDivContent = document.getElementById(
        `slide-${slideIndex}`
      ).innerHTML;

above is the code i am using to create a new tab and write an existing div onto that tab. i would like to call an api when the new window that is opened is refreshed or closed.
tried using these listeners below.

 window.addEventListener("beforeunload", function(event) {
    // Prevent the user from leaving the page.
    console.log('tried closing the window')
    event.preventDefault();
  });
  
  function checkWindowClosed() {
    if (window.closed) {
      console.log('window closed')
    } else console.log('still open')
  }
  
  setInterval(checkWindowClosed, 1000);

  • 1

    You can’t reliably detect a child window being closed from the parent. A better approach would be to detct the content of the child window being unloaded and use a Beacon to send your API request. Better still, don’t use the popup at all, as it’s likely to be blocked in modern browsers as popups are just plain annoying, and use a modal dialog in the current page instead.

    – 




  • 1

    Shouldn’t you be checking it on newWindow and not window?

    – 

  • I think the pagehide event could be useful here.

    – 

  • @RoryMcCrossan, not using window.open() to create a popper, wanted a feature that would create a new window open and user would be able to use that as an extended display. for which i am using window.open(). i dont think modal would be useful for that usecase

    – 

want to add the listener to the newWindow you created using window.open()?

With a little error checking we’ll know if accessing the window is successful…

try{

 newWindow.document.body.appendChild('<div>hello</div>'); // or some other operation

} catch(e){

 alert(e);

}

Leave a Comment