How do I detect if the HTML5 autoplay attribute is supported?

前端 未结 9 760
遇见更好的自我
遇见更好的自我 2020-12-05 05:04

How do I best detect whether a browser\'s HTML5 video element supports autoplay?

On current iOS Safari, for example, autoplay is disabled.

Update:

9条回答
  •  猫巷女王i
    2020-12-05 05:05

    I realize this is a video question - and it applies to audio too.

    I have built an audio test with the intention of loading it into Moderizr with Modernizr.addTest().

    The results are surprising and very dependent on platform and system state. Turns out there are several Android browsers that support autoplay. Who knew.

    From looking at GitHub, I imagine the Modernizr guys will figure all this out more reliably and elegantly than I have - if they haven't already. It seems to boil down to timing. You'd think the browsers guys would throw us a bone here. Maybe they will.

    Anyway, here is the jsfiddle link: Audio().autoplay test.

    While there is fluff code in the jsfiddle example, here's the core:

    var supportsAutoplay = false; //assume
    var audio = new Audio();
    var waitTime;
    audio.autoplay = true;
    audio.volume = 0;
    
    // this will only be triggered if autoplay works
    audio.addEventListener('play', function () {
        supportsAutoplay = true;
    });
    
    audio.src = testSrc; //see if the listener is listening
    
    setTimeout(          //wait for listener to run
        function(){
            return supportsAutoplay;
        },
        waitTime
    ); 
    

    While I have not seen one with a setTimeout other than the one above (the Modernizr guys talk about it), there are several versions of this code around. I guess I'll credit Peter Coles. Maybe his version is less likely to suffer from timing issues.

提交回复
热议问题