Last active
October 18, 2018 13:35
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())) | |
}) | |
} |
Author
JoostKiens
commented
Oct 1, 2018
•
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()
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