检测特定选项卡何时关闭

时间:2016-03-16 20:36:09

标签: javascript window focus detect

我正在运行一个生成可下载文件的.php文件;当.php文件运行时,它会在浏览器中打开一个选项卡。有时,.php文件最多需要15秒,具体取决于创建文件的条件。

我想知道此选项卡何时打开,生成可下载文件以及何时关闭。这样,我可以在生成文件时显示某种加载消息。完成.php文件创建文件后,它会自动关闭选项卡。

代码:

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();

2 个答案:

答案 0 :(得分:0)

为您的窗口提供一个唯一的ID,以便脚本知道要检查哪一个(如果多次打开/关闭,可能需要随机)。我不知道你是否需要专注,弹出许可是你要弄清楚,但我认为以下应该有效:

var win = window.open(download, 'windowID', 'width:300px;height:300px');
win.document.write("<p>One moment please!</p>");
win.focus();

var test = setInterval(function() {   
    if(win.closed) {  
        clearInterval(test);  
        // do you stuff here after window closed
    }  
}, 500); 

答案 1 :(得分:0)

我建议不要在新标签页中打开PHP文件,但使用XMLHttpRequest(),您可以在MDN上找到有关如何使用它的指南

你可以像这样使用它:

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();
相关问题