

Checking for undefined prevents this code from failing with an error on older versions of web browsers. Returning a promise to allow you to determine success or failure of the operation was added more recently.

We check for this because in earlier versions of the HTML specification, play() didn't return a value. The first thing we do with the result of play() is make sure it's not undefined. play ( ) if (startPlayPromise != undefined )

That means that the first time the play event is fired, you know your media is being started for the first time after the page is opened. The play event is sent both when the media is resumed after being paused and when autoplay occurs. You can do this easily, by listening for the play event to be fired on the media element. All you can really do is examine a few values and make an educated guess as to whether or not autoplay worked.Ī better approach, if you're able to adjust the direction you look at things from, is to instead rely on knowing that playback of the media has successfully started, instead of when it fails to start. Nor is there an exception thrown or a callback you can set up or even a flag on the media element that tells you if autoplay worked. There's not an event triggered when autoplay fails. Unfortunately, in the case of the autoplay attribute, recognizing whether or not autoplay successfully began is tricky. If you rely on autoplay for anything important, or if autoplay failure will impact your app in any way, you will probably want to be able to tell when autoplay didn't begin.
