On my page, I have an event listener for audio file hyperlinks:
link.addEventListener("click", async (e) => {
e.preventDefault()
const filelink = link.pathname
if((await fetch(filelink,{method: 'HEAD'})).ok == true) {
audiodlg.showModal()
player.src = filelink
document.querySelector("dialog > span").innerText = filelink.substring(filelink.lastIndexOf('/')+1)
} else { alert("The audio for this lesson is not available right now. Please check back in a little bit.") }
On Chromium (Edge actually), if the file does exist, I get this console msg:
If the file does not exist, the browser shows the alert and reports the 404 along with a fetch failure:
Can someone explain why Chromium reports a failed fetch?
I used the HEAD method as a lightweight way to check if the file exists; if there is a better way to do this I’m all ears!
I also just discovered that the HEAD check creates ~10s delay in opening the audio player after clicking the file link but only on a mobile browser (Chrome or Firefox, tested on Wi-Fi). Any ideas how this could be?
Okie dokie. It seems it might be a quirk with Chromium that it shows this ‘failure’ if you don’t actually read the response. If I execute .text() then the failure does not show. I didn’t see a way on the fetch API to disregard/suppress the body.
I’d still appreciate any help with the delay using mobile or a better method to check for existence of a file.
Hi @ebooks91 I just tried with an actual chromium and didn’t get this behaviour… maybe it’s indeed an edge quirk. Anyway, you could just add the source directly and add an error event listener to the player:
Thanks for that suggestion - interesting, I didn’t think of an event listener. However, I couldn’t get it to work as I’d like because it won’t stop the player modal from displaying. The modal is triggered by a click event listener, and I discovered I can’t have a listener in a listener
Well technically you can, but it’s rarely a good idea as it quickly gets messy and hard to reason about. You can however programmatically close your modal like so (assuming it’s a dialog element):
Having the error listener is a suitable solution. It still shows the dialog (which I would rather not show at all in this scenario), but still works nicely.
I can’t use the audio ‘canplay’ event because there is no opportunity to pop the alert upon the error condition.