Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get download progress of an IFRAME

I would like to display a progress of downloading some document inside an iframe. I've created this JavaScript progress bar and now I want to use it as a download progress indicator. I know it's possible when used with ajax, but what about loading file/document in a traditional way.

I've tried to search inside MSDN for the solution and I'm now wondering if I could use any of these:

  • window.onreadystatechange / document.onreadystatechange
  • document.onprogress event - I'm not sure if it's supported by other browsers than IE and if it's applied to download progress at all.

or should I look somewhere else...?

like image 711
Piotr Salaciak Avatar asked Nov 26 '22 14:11

Piotr Salaciak


1 Answers

Well... 11 years later, I see it goes unanswered, but your progress bar still exists!

I was looking for the same thing and ended up using a fetch, implementing this enhancement: https://github.com/AnthumChris/fetch-progress-indicators/blob/master/fetch-enhanced/supported-browser.js

This piece of code checks the amount of data read of fetch response against the content-length header, and turns it into an easy to use hook. One can also implement something similar themselves, if preferred.

Then you can do something like:

let progress = 0;
const fetcher = new ProgressReportFetcher({loaded, total} => {
  progress = (loaded / total) * 100;
});

let iframeSrc;
fetcher.fetch(resourceUrl)
  .then((response) => response.arrayBuffer())
  .then((arrayBuffer) => new Blob([arrayBuffer], { type: 'application/pdf' })) // see note below
  .then((blob) => window.URL.createObjectURL(blob))
  .then((url) => {
    iframeSrc = url;
  });

(Or, if you want to port it back to javascript 11 years ago, some jquery variant of this...)

N.b., I turned it into a PDF here. You need to set the mimetype when making the blob, otherwise you see garbled data, and the native response.blob() method unfortunately does not support doing this. Hence the extra jump through the arrayBuffer.

like image 74
xor Avatar answered Dec 09 '22 20:12

xor