According to this question:
Is there a way to detect the start of a download in JavaScript?
There is no programmatic way to detect when a download begins. That question is six years old now, so perhaps it is out of date, but I could not find any more recent information to contradict it.
An alternative approach would be to break the download process into two parts so that you can control when the actual data transfer begins:
- Instead of initiating the download immediately, have the button send an AJAX request to the server asking it to prepare the file for download.
- The server should not reply to the AJAX immediately, but should prepare the file and save it in a temporary file storage area with a unique generated name/ID.
- Once the file is ready, the server should reply to the AJAX with the name/ID of the file.
- On the client, the AJAX completion callback can play the sound, since it knows the download is about to begin.
- It then uses
window.open()
to request the file from the server.
- Now the server can respond with the appropriate headers as you used to do.
- Finally, the server can delete the file from temporary storage (or just wait for a
cron
job to do it).