HTMLVideoElement.play may be undefined
See original GitHub issueAccording to MDN, “older browsers may not return a value from play()
.” I also got an alert about that in production shortly after deploying a change that used play().catch()
without checking if the Promise
was undefined
.
There’s another mention to that in MDN’s “Autoplay guide for media and Web Audio APIs”:
[…] You might use code like this to accomplish the job:
let startPlayPromise = videoElem.play(); if (startPlayPromise !== undefined) { startPlayPromise.then(() => { // Start whatever you need to do only after playback // has begun. }).catch(error => { if (error.name === "NotAllowedError") { showPlayButton(videoElem); } else { // Handle a load or playback error } }); }
The first thing we do with the result of
play()
is make sure it’s notundefined
. We check for this because in earlier versions of the HTML specification,play()
didn’t return a value. Returning a promise to allow you to determine success or failure of the operation was added more recently. Checking forundefined
prevents this code from failing with an error on older versions of web browsers.
I have never contributed to this repo, but I am happy to write a PR if the change makes sense!
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (4 by maintainers)
Top GitHub Comments
I think it’s safe to close this. 👍
@github-actions close
@saschanaz Thanks for the clarification and for updating the MDN article! I wasn’t sure how old is too old for still providing static type support, so if this scenario doesn’t pass the criteria we can close the issue.