检测特定选项卡何时关闭

Detect When Specific Tab Closes

本文关键字:何时关 选项 检测      更新时间:2023-09-26

我有一个.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();

我建议不要在新选项卡中打开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();

给你的窗口一个唯一的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);