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

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

问题描述

假设我们有以下 HTML 文件:

<头><title>测试 iframe 下载</title><script type="text/javascript">无功初始化= 0;函数下载(){document.getElementById("dload_frame").src = "http://example.com/dload.py";}功能警报(){如果(初始化== 0){初始化 = 1;}别的 {document.getElementById("alert_span").innerHTML = "明白了!";}}<身体><span id="alert_span">主要内容.</span><br/><input type="button" value="Download" id="btn" onclick="download()"/><iframe id="dload_frame" src="http://404.com/404" onload="alert()"></iframe>

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

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

有什么解决办法吗?不需要使用 iframe,期望的行为是在浏览器开始下载提供的文件后启动回调.

解决方案

我也遇到过这样的问题:这是我的解决方法,请看看它是否适合您:

<div style="display:none" id="frameDiv">

<button onclick="download()">下载文件</button>

据我所知,iframe 的 onload 事件只触发一次.为 src 属性设置另一个值不会导致 onload 事件再次触发.

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>

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.

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.

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>

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天全站免登陆