Youtube API Dynamic iFrame

2019-07-14 04:50发布

问题:

I'm trying to load a youtube video dynamically (iframe is generated on click after the page has loaded) with the ability to control the playback using the Youtube API.

What I have found is that if the iFrame is not present on the page when the API is loaded I can't seem to get the controls to work. What am I doing wrong? (I would like to avoid a solution that includes having the iframe present on the page when it is loaded)

Here's some example code: https://jsfiddle.net/nu1y9oe8/5/ (Click on the black box to generate the iframe and play the video. Once the video is playing try to hit the pause button)

How could I bind the API to the iframe once it has been created on click so that the pause button works?

'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();
  });

})();    

Any help would be greatly appreciated, Thanks!

回答1:

Small typo in enbalejsapi=1 should be enablejsapi=1

Add iframe sandbox attributes so that outer script can access the iframe

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