0

I'm adding a video background to my site, that will autoplay when the page loads. The autoplay is intermittent at the moment, and may be affected by ajax calls elsewhere on the page.

When the video doesn't autoplay, i get the following error:

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

function addVideoBackground() {

    // SWITCH WHICH VIDEO //

    const urlPath = window.location.pathname;
    let videoSrc;

    switch (urlPath) {
        case "/pages/home-recognition":
            videoSrc = "https://player.vimeo.com/external/574413787.hd.mp4?s=717309f70fd17c0204187701b2316787944a1fce&profile_id=174";
            break;
        default:
            videoSrc = "https://player.vimeo.com/external/574413787.hd.mp4?s=717309f70fd17c0204187701b2316787944a1fce&profile_id=174";
    }

    // DECLARE VARIABLES //
    const body = document.querySelector('header');

    //CREATE BASIC ELEMS //
    const videoHolder = document.createElement('div');
    const videoOuter = document.createElement('div');
    const videoElem = document.createElement('video');
    const source = document.createElement('source');

    // APPLY ATTRIBUTES
    $(videoHolder).addClass("videoHolder");
    $(videoOuter).addClass("videoOuter");
    $(videoElem).attr({ autoplay: "true", muted: "true", loop: "true", id: "videoBackground" });
    $(source).attr({ src: videoSrc, type: "video/mp4" });

    // PUT IT ALL ON SITE //
    videoElem.appendChild(source);   
    videoOuter.appendChild(videoElem);
    videoHolder.appendChild(videoOuter);
    body.appendChild(videoHolder);

}

window.addEventListener('load', async () => {
  addVideoBackground()
  let video = document.querySelector('video[muted][autoplay]');
  try {
    await video.play();
  } catch (err) {
    video.controls = true;
  }
});

1 Answers1

1

Chrome has released a new policy in 2018, in which autoplay will not work as expected until there has been a user interaction on the page.

You can refer to this link to know more about it: https://developer.chrome.com/blog/autoplay/#developer-switches

Thanveer Shah
  • 3,250
  • 2
  • 15
  • 31
  • Thanks for your response. I've read this policy, it states that muted autoplay is always allowed. My code adds a muted attribute to the video, but it still doesn't autoplay. – user3113415 Aug 04 '21 at 13:04