1

I have looked in many threads but cannot find an answer that works with current chrome & IE ...

I want to download a file (from the same domain as the page, no CORS issues) and save it locally and I also need a callback when the download is done in order to turn off my 'downloading' notification.

I tried with a hidden iframe like this:

// to download a file we don't want to use window.location.assign because in case of error the broswer
// will redirect to the error page, instead we create an invisible iframe and set src to it
function downloadToFile(url, done) {
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    document.body.appendChild(iframe);
    iframe.setAttribute('src', url);

    if (done) {
        const doc = iframe.contentDocument || iframe.contentWindow.document;
        const inter = setInterval(() => {
            if (doc.readyState === "complete") {
                clearInterval(inter);
                done();
            }
        }, 50);
    }
}

However this does not work - Chrome seems to set the iframe's readyState to 'complete' immediately and so done is called while the file is still loading.

How can this be achived ?

(I also tried to hook a 'load' event but it seems it is not called in chrome and the standard says no iframe events are guaranteed).

kofifus
  • 17,260
  • 17
  • 99
  • 173

0 Answers0