Question

I'd like to sniff out platforms (mobile, tablet) that don't support video autoplay. Is there a trusted way to do this? As of now my only other alternative seems to be a full useragent sniffer.

Related: Is a @media query for landscape or portrait reliable for sniffing handheld devices? I'd imagine if a device returns "landscape" or "portrait", that it is likely a handheld device, and therefore somewhat unlikely to support autoplay?

Thanks for adding to this discussion!

Was it helpful?

Solution

the landscape or portrait queries will only really tell you the aspect ratio of the browser window, so not reliable

in theory the handheld media query will respond correctly for current browsers and in a media query it seems to work

<style> 
@media handheld only { body { background: #00ff00};}
</style>

however when testing the handheld property in code I've not had much luck (handheld is always returning false for me, and screen always returns true for instance)

if (window.matchMedia('handheld').matches) {
    // do some code for a handheld device
}

so... time for a plan B

the only way I can think to reliably test for this is to try and autoplay, and at the same time trigger a timer... if the video doesn't start playing when the timer triggers then assume it can't. It's not an elegant solution (and there will be some fudging required to get the timer right to account for the size of the video/buffering etc) and you'll probably want to cookie the result so you don't have to waste start-up time on subsequent visits.

In this sample I use a .5s delay, and check against the progress event on the <video> tag... depending on your scenario and the size of video etc you might want to experiment. Tested this on iPad, Nexus7, Nexus4 and Kindle HDX and seems to be fairly reliable

<video id="videoPlayer" autoplay controls>
    <source src="Video.mp4" type="video/mp4">
</video>

<script>
var playing = false
var waitAndSee = 500; // this allows 0.5s for the video to show progress

var video = document.getElementById('videoPlayer');
video.addEventListener('progress',function(e){
    playing = true
}); 

var counter=setTimeout ( "didItStart()", waitAndSee );

function didItStart() { 
    clearTimeout(counter);
    if (playing) {
    document.write("it started")
    } else {
    document.write("it didn't")
    }
}

</script> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top