3

I'm using a hidden iframe in an HTML page for downloading purposes. And I would like to know when it's done. I've searched the Internet a lot and everyone says that I should use iframe's onload event handler but it's not working for me in Chrome!

I'm not sure where but I read somewhere that it's because I'm downloading files with my iframe instead of HTML documents. And I must admit that it's specific to Chrome and it works fine in FireFox.

I've also tested readstate and onreadystatechange without success.

I've created a fiddle to demonstrate the problem:

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>
Mehran
  • 15,593
  • 27
  • 122
  • 221

1 Answers1

-2

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>
alessandrio
  • 4,282
  • 2
  • 29
  • 40
  • 2
    Thanks, it would nice to point out that the problem relies in the order of code and that `iframe.src = url;` should be done at the end. – Mehran Sep 19 '14 at 17:47
  • 1
    This doesn't seem to work anymore, at least in Firefox. The event never fires. – John Dvorak May 10 '16 at 11:56
  • [check here](http://stackoverflow.com/questions/16689273), [and here](http://stackoverflow.com/questions/4548984), [last](http://stackoverflow.com/questions/9249680) – alessandrio May 13 '16 at 14:38
  • 2
    This does not work, tested in latest Firefox and Chrome – Matt Cosentino Mar 10 '17 at 23:44