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

How Can I Reliably Detect File Download Completion in a Browser without Consistent 'load' Events?

DDD
DDDOriginal
2024-12-18 05:56:15881browse

How Can I Reliably Detect File Download Completion in a Browser without Consistent

Detecting File Download Completion in Browsers

Dynamic file generation and download can be a challenge when it comes to providing feedback to users. This article examines a scenario where a server generates a file in response to a request, but the browser doesn't provide a clear indication of when the download is complete.

The Problem: Event Detection Limitations

The author had difficulty detecting the download completion in their scenario where the file was generated dynamically and saved in a hidden iframe. The "load" event on the iframe didn't trigger consistently across browsers, leading to an unreliable indicator.

Alternative Solution: Client-Side Polling

One solution involves using a client-side polling mechanism in JavaScript. The algorithm works as follows:

  • A unique token is generated and included in the download request.
  • The browser shows a "waiting" indicator.
  • A timer is started that checks for a cookie with the name "fileDownloadToken" periodically.
  • If the cookie is present and matches the token, the "waiting" indicator is hidden.

Server-Side Response

The server-side code responds by setting a cookie with the name "fileDownloadToken" when the request contains a non-empty token value. This cookie serves as a signal to the client-side code that the download is complete.

Code Implementation

Example client-side JavaScript:

function blockResubmit() {
  // ...
  downloadTimer = window.setInterval(function() {
    var token = getCookie("fileDownloadToken");

    if (token == downloadToken || attempts == 0) {
      unblockSubmit();
    }

    attempts--;
  }, 1000);
}

Example server-side PHP:

$TOKEN = "downloadToken";

// Sets a cookie so that when the download begins the browser can
// unblock the submit button.
$this->setCookieToken($TOKEN, $_GET[$TOKEN], false);

$result = $this->sendFile();

Benefits of this Approach

  • It doesn't require temporary file creation on the server.
  • It's compatible with multiple browsers.
  • It provides a reliable way to detect download completion in the specified scenario.

The above is the detailed content of How Can I Reliably Detect File Download Completion in a Browser without Consistent 'load' Events?. 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