2

我试图通过使用Youtube API控制回放的能力来动态加载YouTube视频(在页面加载后点击时生成iframe)。Youtube API动态iFrame

我发现的是,如果加载API时页面上不存在iFrame,我似乎无法让控件工作。我究竟做错了什么? (我想避免一个解决方案,包括加载时在页面上显示iframe)

下面是一些示例代码:https://jsfiddle.net/nu1y9oe8/5/(单击黑色框以生成iframe并播放视频。一旦视频正在播放尝试点击暂停按钮)

如何将API绑定到iframe,一旦它已经在点击创建,以便暂停按钮的作品?

'use strict'; 

var player; 

// Call the youtube api 
var tag = document.createElement('script'); 
tag.id = 'iframe-demo'; 
tag.src = 'https://www.youtube.com/iframe_api'; 
var firstScriptTag = document.getElementsByTagName('script')[0]; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

// Is the api ready 
function onYouTubeIframeAPIReady() { 
    console.log('api is ready'); 
} 

(function() { 

    var youtube = document.querySelectorAll(".youtube"); 

    for (var i = 0; i < youtube.length; i++) { 

    youtube[i].addEventListener("click", function() { 

     var iframe = document.createElement("iframe"); 

     iframe.setAttribute("id", "test-api"); 
     iframe.setAttribute("frameborder", "0"); 
     iframe.setAttribute("allowfullscreen", ""); 
     iframe.setAttribute("src", "https://www.youtube.com/embed/"+ this.dataset.embed +"?rel=0&showinfo=0&autoplay=1&enbalejsapi=1"); 

     this.innerHTML = ""; 
     this.appendChild(iframe); 

     player = new YT.Player('test-api'); 

     console.log(player); 
    }); 

    } 

    var pause = document.querySelector('.pause'); 

    pause.addEventListener('click', function() { 
    player.pauseVideo(); 
    }); 

})();  

任何帮助将不胜感激, 谢谢!

+0

请你详细说明... – 2016-10-03 07:42:15

回答

2

enbalejsapi=1小错字应enablejsapi=1

添加iframe的sandbox属性,使外部脚本可以访问你想达到什么的iframe

iframe.setAttribute("sandbox", "allow-same-origin allow-scripts");