Skip to content

Latest commit

 

History

History
57 lines (44 loc) · 1.78 KB

download-iframe.md

File metadata and controls

57 lines (44 loc) · 1.78 KB
标题 标签
downloadIframe(监听 iframe 下载完成) iframe,download(内联框架,下载)

通过定时器轮询监听readyState的状态,如果值是complete或者interactive说明文件下载完成。

  • 使用定时器以及递归,传入一个文件下载路径path。
  • 如果不传入第二个参数,则使用默认的1s作为轮询时间。
  • 第三个参数作为当下载成功之后的回调函数。

代码如下:

const downloadIframe = (path, resolve, time = 1000) => {
  let iframe = document.createElement('iframe');
  iframe.src = path;
  iframe.style.display = 'none';
  document.body.appendChild(iframe);
  let timer = null;
  let handler = function () {
    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
    if (['complete', 'interactive'].indexOf(iframeDoc.readyState) > -1) {
      document.body.removeChild(iframe);
      if (timer) clearTimeout(timer);
      resolve('success');
    } else {
      timer = setTimeout(handler, time);
      resolve('downloading');
    }
  };
  handler();
};

ts 代码如下:

调用方式:

downloadIframe('XXX.txt', status => {
  if (status === 'success') {
    //下载完成之后的操作
  }
});

应用场景

以下是一个实战示例:

结果如下:

<iframe src="codes/javascript/html/download-iframe.html"></iframe>