0
votes

I want to play the video once the users viewport intersects with the video or pause it once video gets out of the view. I managed to do it on Firefox, but it seems like Chrome has some issues.

What I get is the error in the console:

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

I googled a bit and found there is a catch with muted="muted" to play the video automatically. That works, but I do need a sound as well.

I've tried to programmatically unmute the video, but it doesn't work. Also, I've tried to trigger events and other things in hope it will do the trick, i.e. create false positive user interaction, but no luck.

I was asking myself, how could YouTube achieve autoplay with sound (before any user interaction)?

The code is the following:

var onIntersection = function(entries, observer){
    entries.forEach(function(entry){
        if( entry.isIntersecting && entry.intersectionRatio >= 0.5){
            entry.target.play();
        }else{
            entry.target.pause();
        }
    });
};

if( 'IntersectionObserver' in window ){

    var observerOptions = {
        threshold: [0, 0.5]
    };

    var observer = new IntersectionObserver(onIntersection, observerOptions);

    $('video').each(function(){
        observer.observe($(this)[0]);
    });
}

HTML:

<video inline playsinline autoplay loop style>
    <source src="..." type="video/mp4">
</video>
1

1 Answers

0
votes

chrome is prevented from any spam in the browser. Just add this $(body).trigger('click') or muted="true" on your attr video, it's will be find.