如何在iframe中下载文件时触发onload事件?

dpq*_*dpq 11 iframe download onload

假设我们有以下HTML文件:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test iframe download</title>
<script type="text/javascript">

var init = 0;

function download() {
  document.getElementById("dload_frame").src = "http://example.com/dload.py";
}

function alert() {
  if (init == 0) {
    init = 1;
  }
  else {
    document.getElementById("alert_span").innerHTML = "Got it!";
  }
}

</script>
</head>
<body>

  <span id="alert_span">Main content.</span><br/>
  <input type="button" value="Download" id="btn" onclick="download()" />
  <iframe id="dload_frame" src="http://404.com/404" onload="alert()"> </iframe>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

现在,如果iframe的src被重写到的URL(在这种情况下 - " http://example.com/dload.py ")返回HTML,没问题:onload事件触发,span的内容被替换,每个人的快乐.

但是,如果URL返回的文件的内容类型设置为强制浏览器打开保存文件对话框的内容,则iframe的onload事件永远不会触发.

有没有解决方法?不需要使用iframe,所需的行为是在浏览器开始下载提供的文件后启动回调.

jer*_*jer 1

我遇到了与此相同的问题:这是我的解决方法,请看看它是否适合您:

<script>
 function download(){
    var url = 'http://example.com/dload.py';
    var htm = '<iframe src="' + url +'" onload="downloadComplete()"></iframe>';
    document.getElementById('frameDiv').innerHTML = htm;
 }
</script>

<div style="display:none" id="frameDiv">
</div>
<button onclick="download()">download file</button>
Run Code Online (Sandbox Code Playgroud)

据我记得 iframe 的 onload 事件只触发一次。为 src 属性设置另一个值不会导致 onload 事件再次触发。