自动关闭带有要下载的文件的弹出窗口

2022-01-20 00:00:00 download popup php javascript

我有一个文件,名为 download.php,其中包含一个要下载的文件,所以它有以下标头(用 PHP 声明):

I have a file, named download.php, which contains a file to be downloaded, so it has the following headers (declared with PHP):

header("Content-Type: ".pathinfo($_GET['file'], PATHINFO_EXTENSION));
header("Content-Length: ". filesize($_GET['file']));
header("Content-Disposition: attachment; filename=". $_GET['file']);

download.php 由其他页面作为弹出窗口使用 jQuery 打开.

download.php is opened as a popup with jQuery by an other page.

现在我希望 download.php 在几秒钟后自动关闭(使用 JavaScript)(所以我可以确保下载开始),但我没有设法编写工作代码.以下是我尝试过的代码(我将它们放在 标题之后):

Now I want download.php to self-close (using JavaScript) after some seconds (so I'm secure that download started) but I didn't manage to write working code. Here are the codes I tried (I placed them after headers):

window.setTimeout('self.close();', 3000);
window.setTimeout('function(){self.close();}', 3000);
window.setTimeout(self.close();, 3000);

我也简单试过:

self.close();

但它无论如何都不起作用.

but it does not work anyway.

我尝试将这些代码放在 <head><body> 中.

I tried to put these codes both in <head> and in <body>.

可能是什么问题?

推荐答案

我能问一下在这个打开的窗口中浏览器 url 栏中显示的内容吗?可能是浏览器看到的标题让浏览器知道它将被视为下载并且不会将窗口作为真实页面运行.而是打开类似'about:blank'的东西.如果是这种情况,页面上的 javascript 将永远不会运行.

Can I ask what it says in the browser url bar in this opened window. It might be the case that the browser see's the headers letting the browser know it is to be treated as a download and doesn't run the window as a true page. and instead opens something like 'about:blank'. If that's the case the on the page javascript would never get run.

不过,我可以提出以下建议.我假设这个窗口正在被另一个页面打开.在这种情况下,让另一个页面通过 javascript 以编程方式打开窗口并从那里控制关闭.

I can suggest the following however. I'm assuming this window is being opened by another page. In that case have the other page open the window programatically through javascript and control the close from there.

var popout = window.open("http://example.com/download.php");
window.setTimeout(function(){
    popout.close();
}, 1000);

相关文章