Muirik
Muirik

Reputation: 6289

Safari Error When Playing Video in React App

In my React app I am running into an issue in Safari (this works fine in Chrome and Firefox) where, when I mouseover a video to play it, I get the following error:

NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

The relevant code block is this:

{ this.state.url ? 
  <video className="video"
    onMouseOver={event => {
      this.onVideoPlay(this.state.url, event);
    }}
    onMouseOut={event => {
      this.onVideoPause(this.state.url, event);
    }}
    src={`${this.state.url}`} >
  </video>
  : null
}

And my two functions look like this:

  onVideoPlay = async (videoUrl, event) => {
    if (!videoUrl || !event || videoUrl === 'url(${videoBg})') return;
    if (!this.state.isPlaying) {
      await event.target.play();
      this.setState({ isPlaying: true });
    }
  };

  onVideoPause = async (videoUrl, event) => {
    if (!videoUrl || !event) return;
    if (this.state.isPlaying) {
      await event.target.pause();
      this.setState({ isPlaying: false });
    }
  }

What is the issue here, and how can I resolve it?

Upvotes: 0

Views: 4369

Answers (1)

David Ballester
David Ballester

Reputation: 577

If I had to bet, I'd say the issue is trying to play a video unmuted without direct user interaction.

According to Safari docs:

A element can use the play() method to automatically play without user gestures only when it contains no audio tracks or has its muted property set to true. If this video element gains an audio track or becomes unmuted without a user gesture, playback pauses. Playback stops if the video element isn't visible onscreen or is out of the viewport.

Configuring the video to play muted should solve the issue, as the MDN guide for autoplay also states.

You can argue that, in your case, you do have a user gesture, mouseover. But that doesn't count as interacting with the site. It has to be a click or a keypress, as the webkit blog specifies.

Does it work with click, for instance?

Upvotes: 2

Related Questions