是否可以从嵌入式youtube iframe中获取<video>元素?

时间:2019-01-09 02:27:17

标签: javascript html5 youtube youtube-api youtube-iframe-api

目前,我正在研究放大嵌入的youtube视频的可能性。因此,我在iframe中设置了一个播放器(为此我正在使用popcorn.js HTMLYoutubeElement)

player = new YT.Player( elem, { width: "100%", height: "100%", wmode: playerVars.wmode, videoId: aSrc, playerVars: playerVars, events: { 'onReady': onPlayerReady, 'onError': onPlayerError, 'onStateChange': onPlayerStateChange } });

出于这个目的,我希望从此iframe中访问<video>元素。 使用youtube iframe API,我可以通过player.getIframe()获得合适的iframe。但是,一旦我尝试使用“

”获取“内部”文档,

var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

我收到以下错误消息:

  

未捕获到的SecurityError:阻止了源为http://localhost:3000的帧访问跨源帧。

This kind of error is discussed here but without helping alot with my specific problem

并且看着youtube iframe API,我找不到直接访问<video>元素的任何可能性。因此,我的问题是:真的有可能吗?

1 个答案:

答案 0 :(得分:0)

您甚至无法缩放视频,这样会降低视频质量。 如果您想以全屏模式播放视频,那么也许就是您搜索的内容:

var player, iframe;
var $ = document.querySelector.bind(document);

// init player
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
   height: '100%',
   width: '100%',
   videoId: 'xxxxxxxxxxx',
    events: {
     'onReady': onPlayerReady
    }
 });
}
// when ready, wait for clicks
function onPlayerReady(event) {
 var player = event.target;
 iframe = $('#player');
 setupListener(); 
}

function setupListener (){
  $('button').addEventListener('click', playFullscreen);
}
// when ready, wait for clicks
function onPlayerReady(event) {
    var player = event.target;
    iframe = $('#player');
    setupListener(); 
}

function setupListener (){
    $('button').addEventListener('click', playFullscreen);
}

function playFullscreen (){
   //won't work on mobile
   player.playVideo(); 
   var requestFullScreen = iframe.requestFullScreen || 
   iframe.mozRequestFullScreen || 
   iframe.webkitRequestFullScreen;
   if (requestFullScreen) {
      requestFullScreen.bind(iframe)();
   }
}