Search code examples
javascriptwindowfocusdetect

Detect When Specific Tab Closes


I have a .php file running that is generating a downloadable file; when the .php file runs it opens a tab in the browser. Occasionally the .php file takes up to 15 seconds depending on the conditions to create the file.

I would like to know when this tab is open generating the downloadable file and when it closes. This way I can have some sort of loading message displayed while the file is being generated. When the .php file is done creating the file it automatically closes the tab.

Code:

var win = window.open(download, '_blank'); //opens the php file which generates the file.
if (win)
{
    win.focus();
    //have some sort of message stating to wait for the file to download here and then close it when the php file finishes running.
}
else
{
    alert("Please allow popups.");
}

closePopup2();

Solution

  • I would suggest not opening a PHP file in a new tab, but using XMLHttpRequest(), you can find a guide on how to use it on MDN

    You can use it like this:

    function reqListener () {
      console.log(this.responseText); // Will log full output of page
    }
    
    var oReq = new XMLHttpRequest();
    oReq.addEventListener("load", reqListener);
    oReq.open("GET", download);
    oReq.send();