TypeScript-DOM-lib-generator icon indicating copy to clipboard operation
TypeScript-DOM-lib-generator copied to clipboard

HTMLVideoElement.play may be undefined

Open alcar opened this issue 4 years ago • 4 comments

According 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 not undefined. 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 for undefined 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!

alcar avatar Jun 21 '21 17:06 alcar

Yeah, I think this is reasonable - I'd wait a week or two before looking at contributing because this repo will be a bit of a moving target

orta avatar Jun 28 '21 17:06 orta

Thanks for the tip, I'll look into it in a couple of weeks then!

alcar avatar Jun 28 '21 17:06 alcar

I think all of modern browsers have supported promise return type for years, so I'm not very convinced here 🤔

Maybe the MDN article should be fixed instead.

saschanaz avatar Jul 02 '21 22:07 saschanaz

@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.

alcar avatar Jul 06 '21 13:07 alcar

I think it's safe to close this. 👍

@github-actions close

saschanaz avatar Sep 18 '22 11:09 saschanaz

Closing because @saschanaz is one of the code-owners of this repository.

github-actions[bot] avatar Sep 18 '22 11:09 github-actions[bot]