How to get download progress of an iframe?

Member

by jasen , in category: Javascript , 10 months ago

How to get download progress of an iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 10 months ago

@jasen 

Unfortunately, it is not possible to directly get the download progress of an iframe using JavaScript, as the browser does not expose a built-in API for monitoring iframe download progress.


However, you can implement a workaround by estimating the download progress based on the iframe's loading duration. Here's a step-by-step approach to achieve this:

  1. Wrap your iframe inside a container element:
1
2
3
<div id="iframeContainer">
  <iframe id="myIframe" src="your-iframe-url"></iframe>
</div>


  1. Add a progress bar to visualize the download progress:
1
<div id="progressBar"></div>


  1. Use JavaScript to estimate the download progress:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// Get references to elements
const iframeContainer = document.getElementById('iframeContainer');
const myIframe = document.getElementById('myIframe');
const progressBar = document.getElementById('progressBar');

// Function to estimate download progress
function estimateDownloadProgress() {
  const iframeDocument = myIframe.contentDocument || myIframe.contentWindow.document;
  const loadedBytes = iframeDocument.documentElement.innerText.length;
  const totalBytes = myIframe.src.length; // Assuming iframe's src URL length as total size

  const progressPercentage = (loadedBytes / totalBytes) * 100;
  
  // Update progress bar
  progressBar.style.width = progressPercentage + '%';
}

// Add event listener to iframe's load event
myIframe.addEventListener('load', estimateDownloadProgress);


In the code above, we estimate the download progress by comparing the number of loaded bytes with the total size of the iframe's source URL. We assume the length of the src URL as the total size, which is not fully accurate but provides a rough estimation of the progress. Each time the iframe's load event is triggered, the estimateDownloadProgress function is called to update the progress bar based on the estimated progress.


Keep in mind that this workaround is not precise and may not always provide an accurate representation of the actual download progress.