Detect when a browser receives a file download
Track a server-set cookie to detect a file download. Initialize an interval check using JavaScript. As soon as the cookie appears, it means the download has started. At this point, clear the interval and execute any logic that should run post-download.
Use a unique identifier in the cookie to handle concurrent downloads like a juggling pro 🤹♂️!
Additional strategies
Pop-up alert with window.onblur()
Enhance your file download detection with window.onblur()
. It allows you to detect when a browser dialog surfaces, which might be due to a file download:
Security on point!
Improve security by using httpOnly and Secure flags when setting the cookie:
Embrace the stream
Consider streaming data when dealing with larger files:
Advanced approaches and edge cases
Multiple downloads? No problem!
Use a mapping between downloads and tokens to manage several downloads simultaneously:
Timeout and weaker references
Incorporate a timeout to remove the interval check if download completion isn't detected within a pre-set duration:
Prevent memory leaks; clean up is essential!
Other monitoring methods
AJAX pooling
Fetch status updates by polling the server via AJAX:
iframes
Initiate download within an iframe and monitor its loading state:
UX matters!
Inform the user about the progress of the download:
Was this article helpful?