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:
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
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!