Skip to content

Instantly share code, notes, and snippets.

@JoostKiens
Last active October 18, 2018 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoostKiens/a8dd8f3a2c0ccbef875629275822235a to your computer and use it in GitHub Desktop.
Save JoostKiens/a8dd8f3a2c0ccbef875629275822235a to your computer and use it in GitHub Desktop.
Check if browser allows autoplaying of videos, https://webkit.org/blog/6784/new-video-policies-for-ios/
function autoplayVideoSupported(muted = true, playsinline = true) {
const v = document.createElement('video')
v.muted = muted
playsinline && v.setAttribute('playsinline', 'playsinline')
v.setAttribute('width', 0)
v.setAttribute('height', 0)
v.style.opacity = 0
document.querySelector('body').appendChild(v)
return new Promise((resolve, reject) => {
v.play()
v.paused ? reject() : resolve()
// If we remove the video immediately we will get an error: https://goo.gl/LdLk22
// v.play() returns a promise in most browsers, but a video without a source doesn't resolve or reject this promise.
// so we can't use the promise to determine when to remove the test video.
// For now we can use this ugly hack, 2 frames seem to work
window.requestAnimationFrame(_ => window.requestAnimationFrame(_ => v.remove()))
})
}
@JoostKiens
Copy link
Author

JoostKiens commented Oct 1, 2018

autoplayVideoSupported()
  .then(_ => console.log(`can autoplay videos`)
  .catch(_ => console.error('can\'t autoplay, show fallback gif?')

@klaasman
Copy link

See Google's article about "Autoplay Policy Changes"

document.querySelector('video').play()
  .then(_ => {
    // Autoplay started!
  })
.catch(error => {
    // Autoplay was prevented.
    // Show a "Play" button so that user can start playback.
  });

The video.play() will reject with a NotAllowedError when autoplay isn't allowed.

documentation: HTMLMediaElement.play()

@JoostKiens
Copy link
Author

@klaasman

Sure, but this only works in modern browsers, IE11 doesn't return a promise for example.

And if we ignore that situation, the NotAllowedError only occurs if we add a valid src and add the video to the DOM. If we do that a chunk of the video will be downloaded, even if we can not autoplay (14kb on iOS). This is probably acceptable, but as you can see above, it is not necessary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment