如何在iframe中下载文件时触发onload事件? [英] How to trigger onload event when downloading a file in an iframe?

查看:452
本文介绍了如何在iframe中下载文件时触发onload事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下HTML文件:

Suppose we have the following HTML file:

<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>

现在,如果iframe的src被重写的URL(在这种情况下是 http://example.com/dload.py )返回HTML,没问题:onload事件触发,但是,如果URL返回的文件的内容类型被设置为强制浏览器打开保存文件的内容类型,那么该span的内容将被替换,每个人都很高兴。

Now, if the URL to which iframe's src is being rewritten to (in this case - "http://example.com/dload.py") returns HTML, no problem: the onload event fires, the span's contents are replaced, everybody's happy.

对话框中,iframe的onload事件永远不会触发。

However, if the content type of the file returned by the URL is set to something that forces the browser to open the save file dialog, the iframe's onload event never fires.

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

Is there any workaround? Using iframes isn't necessary, the desired behavior is to launch a callback after the browser begins downloading the supplied file.

推荐答案

我遇到与此相同的问题:
这是我的解决方案,请看它是否适用于您:

I have encountered the same problem as this: Here is my work-around, please see if it works for you:

<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>

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

As far as I can remembered iframe's onload event fires only once. Setting another value for src attribute will not cause the onload event to fire again.

这篇关于如何在iframe中下载文件时触发onload事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆