开发者

How to get download progress of an IFRAME

开发者 https://www.devze.com 2023-02-20 19:25 出处:网络
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 pos

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...?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号