title: javascript - download a file and wait for it to finish
body: <p>I have looked in many threads but cannot find an answer that works with current chrome &amp; IE ...</p>
  
  <p>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.</p>
  
  <p>I tried with a hidden iframe like this:</p>
  
  <pre><code>// 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(() =&gt; {
              if (doc.readyState === "complete") {
                  clearInterval(inter);
                  done();
              }
          }, 50);
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>How can this be achived ? </p>
  
  <p>(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).</p>