Muted autoplay videos stop playing in Safari 11.0
The most reliable way I've found is to ensure:
- at least one user interaction on the page (chrome mobile)
- muted attribute on tag (all)
- playsinline attribute on tag (safari)
Which looks like this:
<style>
video {
display: none;
}
video.active {
display: block;
}
</style>
<button id="button">Show video</button>
<video id="video" muted playsinline></video>
<script>
var button = document.getElementById('button');
var video = document.getElementById('video');
button.addEventListener('click', function() {
video.className = 'active';
video.src = 'https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4';
video.play();
});
</script>
One trick is to reuse the same video player for each video. Then it only needs to be activated the first time. Every consecutive play can occur automatically.
I ran into this issue as well for a short mp4 that played in the background of a website. I was able to get a solution working for iOS Safari 11 without the need for JS by qualifying the video tag with controls="true"
and playsinline
.
Example:
<video autoplay loop playsinline muted controls="true" src="~/background.mp4" type="video/mp4"></video>
Note: Safari doesn't support .webm so don't be like me and struggle with that for longer than you'd like to admit.
Yup, it appears Safari is also blocking muted video's (that don't even have sound)...
I have found a workaround, but it isn't pretty and I'm not proud of it:
var ua = navigator.userAgent.toLowerCase();
var is_safari = (ua.indexOf("safari/") > -1 && ua.indexOf("chrome") < 0);
if(is_safari) {
var video = document.getElementById('#video-element-id');
setTimeout(function() {
video.play();
}, 50);
}
I have tried doing this without the timeout, but Safari is rejecting this by throwing a Promise rejection. I don't know why...