Home >Web Front-end >JS Tutorial >How Can I Reliably Detect File Download Completion in a Browser?

How Can I Reliably Detect File Download Completion in a Browser?

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 21:06:49539browse

How Can I Reliably Detect File Download Completion in a Browser?

Handle File Download Completion Detection

Problem:

Detecting when a browser fully receives a dynamically generated file download becomes crucial when displaying waiting indicators. Currently, using an iframe's "load" event fails to address this issue due to browser inconsistencies.

Solution 1: Browser-Based Token Verification

A client-side JavaScript solution involves:

  • Generating a unique token for the download request.
  • Submitting the request with the token.
  • Displaying a "waiting" indicator.
  • Setting a timer to periodically check for a corresponding cookie with the token value.
  • Hiding the indicator upon finding the cookie.

On the server-side, the algorithm:

  • Checks for the token in the request.
  • Sets a cookie with the token value if found.

Code Snippet (JavaScript):

function setFormToken() {
  var downloadToken = new Date().getTime();
  document.getElementById("downloadToken").value = downloadToken;
  return downloadToken;
}

Code Snippet (PHP):

// Set a cookie to unblock submit button when download begins.
$TOKEN = "downloadToken";
$this->setCookieToken($TOKEN, $_GET[$TOKEN]);

Solution 2: Server Polling

Alternatively, a server-side approach involves:

  • Initiating file creation.
  • Polling the server until completion.
  • Downloading the ready file.

This method avoids creating temporary server files. However, it requires client-server communication during the waiting period.

Pros and Cons:

Using a browser token allows for dynamic detection, but may have browser compatibility issues. Server polling is a more reliable but slower option.

The above is the detailed content of How Can I Reliably Detect File Download Completion in a Browser?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn