提问者:小点点

如何在Chrome上动态添加视频到autoplay?[副本]


我正在给我的网站添加一个视频背景,当页面加载时它会自动播放。此时自动播放是间歇性的,可能会受到页面上其他地方的ajax调用的影响。

当视频无法自动播放时,我会出现以下错误:

未捕获(promise中)DomeException:play()失败,因为用户没有首先与文档交互。

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个答案

匿名用户

Chrome在2018年发布了一项新政策,在该政策中,除非页面上出现用户交互,否则autoplay将无法按预期工作。

您可以参考此链接了解更多信息:https://developer.chrome.com/blog/autoplay/#developer-switches