Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect HTML video autoplay prevention

Mobile browsers prevent video autoplay for understandable reasons. I have a video background on a site, so control buttons are out of question, but I thought that I could pop up window with some info and a button, where the user can accept the background video (triggering manual play) or not, and change it to some static pic.

So the question is: is there a way to tell if the autoplay was interrupted by the browser?

I tried onerror but it doesn't fire so I tried to onsuspend as well:

HTML:

<video id='bgvid' src='bgvid.mp4' type='video/mp4' autoplay loop onsuspend='video_suspended()'>

Javascript:

function video_suspended() {
    $bgvideoElement=$("#bgvid").get(0);
        //Check if reason for suspend was completion or browser interruption
        if($bgvideoElement.readyState<1) {
            //Here comes some pop-up window and a button to
            $bgvideoElement.play();
    } 
}

It works pretty well on tablet (Chrome), but on desktop (Chrome) onsuspendkeeps triggering infinitely (Firefox is alright though).

Any ideas on Chrome problem or any alternatives?

like image 262
Torfiks Avatar asked Feb 05 '16 15:02

Torfiks


People also ask

How do I stop videos from playing automatically in HTML?

just use preload="none" in your video tag and video will stop autoplay when the page is loading.

How do I stop video from automatically playing embedded?

To find it, open the browser menu (the three horizontal lines, top right), then choose Settings, Privacy & security, and Settings next to Autoplay. You've got three options, which are fairly self-explanatory: Allow Audio and Video, Block Audio, and Block Audio and Video.

Can you autoplay video in HTML?

The HTML autoplay Attribute is used to specify that the audio/video should automatically start playing when web page is loaded. It is a Boolean attribute. Uses It can be used with <audio> and <video> element.


1 Answers

You can always test if current browser will run video.play() method. This method is asynchronous and returns response or error, https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play.

The algorithm of testing consists of checking if we got the error after trying to run .play().

export const checkUserAgentVideoAutoplay = async () => {
  const video = document.querySelector('#video-bg');

  try {
    await video.play();

    video.setAttribute('autoplay', true);

    console.log('video started playing successfully');
  } catch (err) {
    console.log(err, 'video play error');
    // do stuff in case your video is unavailable to play/autoplay
    // show user that video autoplay was aborted  
  }
}

This is what says the console in Safari, which refuses playing .webm video format

AbortError: The operation was aborted.
"video play error"
like image 96
Viktoriia Krause Avatar answered Sep 25 '22 14:09

Viktoriia Krause