【问题标题】:Detecting an iframe's onload in Chrome when downloading files下载文件时在 Chrome 中检测 iframe 的加载
【发布时间】:2014-09-18 12:13:26
【问题描述】:

我在 HTML 页面中使用隐藏的 iframe 进行下载。我想知道它什么时候完成。我在网上搜索了很多,每个人都说我应该使用 iframe 的 onload 事件处理程序,但它在 Chrome 中不适合我!

我不确定在哪里,但我在某处读到这是因为我使用 iframe 而不是 HTML 文档下载文件。而且我必须承认它是 Chrome 特有的,并且在 FireFox 中运行良好。

我还测试了readstateonreadystatechange,但均未成功。

我创建了一个小提琴来演示这个问题:

function download(url)
{
    var iframe = document.createElement("iframe");
    iframe.src = url;
    iframe.onload = function () {
        console.log('Download completed.');
    };
    document.body.appendChild(iframe);
}
<button onclick="download('http://www.colorado.edu/conflict/peace/download/peace.zip');">Download</button>

【问题讨论】:

    标签: html google-chrome iframe onload


    【解决方案1】:

    function downloadURL(url) {
        var hiddenIFrameID = 'hiddenDownloader',
            iframe = document.getElementById(hiddenIFrameID);
        if (iframe === null) {
            iframe = document.createElement('iframe');
            iframe.id = hiddenIFrameID;
            iframe.style.display = 'none';
            iframe.onload = function () {
                alert('Download completed.');
            };
            document.body.appendChild(iframe);
        }
        iframe.src = url;
    }
    <button onclick="downloadURL('http://www.colorado.edu/conflict/peace/download/peace.zip');">Download</button>

    【讨论】:

    • 谢谢,很高兴指出问题在于代码的顺序,iframe.src = url; 应该在最后完成。
    • 这似乎不再起作用了,至少在 Firefox 中是这样。该事件永远不会触发。
    • 这不起作用,在最新的 Firefox 和 Chrome 中测试
    猜你喜欢
    • 2015-01-02
    • 2013-07-11
    • 2014-07-09
    • 2014-01-01
    • 2019-06-29
    • 2012-05-22
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    相关资源
    最近更新 更多