Youtube API 动态 iFrame [英] Youtube API Dynamic iFrame

查看:44
本文介绍了Youtube API 动态 iFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态加载 youtube 视频(页面加载后点击时生成 iframe),并能够使用 Youtube API 控制播放.

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.

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

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)

这是一些示例代码:https://jsfiddle.net/nu1y9oe8/5/(点击在黑框上生成 iframe 并播放视频.视频播放后尝试点击暂停按钮)

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)

在点击创建后,如何将 API 绑定到 iframe 以便暂停按钮起作用?

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!

推荐答案

enbalejsapi=1 中的小错别字应该是 enablejsapi=1

Small typo in enbalejsapi=1 should be enablejsapi=1

添加 iframe sandbox 属性,以便外部脚本可以访问 iframe

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

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

这篇关于Youtube API 动态 iFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆