HTML5 video autoplay is not always triggered

468 Views Asked by At

I'm creating an autoplay video element by JS, but its play event can't always be triggered.

const video = document.createElement('video')
video.src = 'http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv'
// video.muted = true
video.loop = true
video.autoplay = true

video.addEventListener('canplay', () => {console.log('can')})
video.addEventListener('play',() => {
  console.log('playing')
  // setTimeout(() => {console.log(video.currentTime)}, 5000)
}, true)

https://codepen.io/drafting-dreams/pen/MWyxwRX

3

There are 3 best solutions below

1
On BEST ANSWER

Adding this line of code seems to fix the problem:

video.setAttribute('crossorigin', 'anonymous')

I also found this article on MDN (Mozilla), it clarified the usage of the crossorigin attribute on image element, but it gives useful insight for video element.

0
On

I think you should add:

video.load();
2
On

This is because you've commented video.muted = true. A video with sound can autoplay only at certain conditions (https://developers.google.com/web/updates/2017/09/autoplay-policy-changes)