zxcetera
zxcetera

Reputation: 115

Youtube API playvideo function not working on iframe

I've been looking all day for a solution, I cannot find any, So Here's my problem: I'm trying to play the youtube video on my website which is embeded to another iframe, example

CMS > youtubeapi.html

CMS: <iframe src="youtubeapi.html" frameborder="0" width="100%" height="1000px"></iframe>

youtubeapi.html

<div class="btn-play" onclick="this.nextSibling.style.display='block'; this.style.display='none';">
    <img src="img/thumbnail.png"/>
</div>
<div style="display:none">
    <div id="player"></div>
</div>

youtubeapi.js

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
    height: '600',
    width: '100%',
    videoId: "videoid",
    playerVars: { 
        'autoplay': 1,
        'controls': 0,
        'wmode': 'opaque',
        rel: 0,
        enablejsapi:1,
        'origin': window.location.origin
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange,
    }
  });
}

function onPlayerReady(event) {
    event.target.playVideo();
}
function pauseVideo() {
    player.pauseVideo();
}
  
var done = false;
function onPlayerStateChange(event) {
    switch(event.data){
        case 0:
            player.stopVideo();
            break;
    }
}
function stopVideo() {
    player.stopVideo();
}

$(function(){
    $(".btn-play").on('click',function(){
        player.loadVideoById($("#videoid").val(), 0, "default");
        player.playVideo();
        console.log("play!",player.playVideo());
    
    });
})

Hope you guys can help me :D

Upvotes: 1

Views: 1902

Answers (1)

Please add 'mute': 1, to your YouTube iframe settings - I've read about autoplay is not enabled until video is muted - it's a browser "security" feature.

You can find more information can be found in others Q&A in Stack Overflow.

These are some sources you can check for more information:

Upvotes: 4

Related Questions