Home > front end >  How to create a play a video in Javascript
How to create a play a video in Javascript

Time:11-07

I'm creating a chrome extension (not for new tab) and want to auto play a muted video every time the user goes to a specific website.

I attempted to try it out in CodePen and it's still not playing the video.

// Video BG
let videoContainer = document.createElement("video");
videoContainer.id = "video";
videoContainer.style.backgroundColor = "rgba(236,55,55,.5)";
videoContainer.style.zIndex = "-1";
videoContainer.style.width = "100%";
videoContainer.style.height = "100vw";
videoContainer.style.marginTop = "50x";
videoContainer.style.position = "fixed";
videoContainer.style.top = "0";
videoContainer.src =
  "https://external-content.duckduckgo.com/iu/?u=https://i.pinimg.com/originals/6f/8a/7d/6f8a7d0ce651ac3ee11046c18b57d232.gif&f=1&nofb=1&ipt=8431012b0b8c3e7404333b537bb0e673adedd1bb00ff35ae9f65003423c0855c&ipo=images";
//videoContainer.type = "video/mp4";
videoContainer.muted = true;
videoContainer.autoplay = true;
videoContainer.loop = true;
videoContainer.controls = false;

document.body.append(videoContainer);

I'm pretty new to coding by the way. Thanks to all who can help.

CodePudding user response:

No problem if you are new, you can check in the MDN official documentation, we have the HTMLMediaElement play() method attempts to begin playback of the media. It returns a Promise which is resolved when playback has been successfully started.

  • You can try using this async function to do that! ;)
const videoElem = document.querySelector("#video");
const playButton = document.querySelector("#playbutton");

playButton.addEventListener("click", handlePlayButton, false);
playVideo();

async function playVideo() {
  try {
    await videoElem.play();
    playButton.classList.add("playing");
  } catch (err) {
    playButton.classList.remove("playing");
  }
}

function handlePlayButton() {
  if (videoElem.paused) {
    playVideo();
  } else {
    videoElem.pause();
    playButton.classList.remove("playing");
  }
}

CodePudding user response:

Here is a tutorial you might be interested in:

https://www.w3schools.com/html/html5_video.asp

Hope that helps!

  • Related