如何使用vanilla Javascript暂停嵌入的Youtube视频?

时间:2017-01-17 09:43:29

标签: javascript youtube

我尝试在没有视频相关事件触发器的情况下暂停iframe嵌入式YouTube视频。

我已阅读youtube embedded apithis answerthis one,这是我目前所拥有的内容(由于CORS问题,该视频不会在代码段中播放,但我猜它并不重要。):



<iframe id="video1" width="560" height="315" src="http://www.youtube.com/embed/JFBUJ6kNl28" frameborder="0" allowfullscreen></iframe>

<script type="text/javascript">
  //youtube api to pause video when changing section
  var tag = document.createElement('script');
  tag.src = "//www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  var player = false

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('video1', {});
  }

  function jump() {
    console.log(player);
    if (player) {
      player.pauseVideo()
    }
  }
</script>
<button type="button" onclick="jump()" name="button">pause button</button>
&#13;
&#13;
&#13;

我错过了什么?当我记录它时,播放器对象就在那里,但它会抛出player.pauseVideo() is not a function

3 个答案:

答案 0 :(得分:0)

我找到了解决方案:如this answer所述,您需要将?enablejsapi=1添加到视频网址

  

A :您必须在网址末尾添加?enablejsapi=1/embed/vid_id?enablejsapi=1

不知何故,它不能与我的代码片段一起使用,但在我的实际案例中有效。

答案 1 :(得分:0)

您可以简单地使用:

iframe.contentWindow.postMessage(message, origin);

从parentWindow向iframeWindow发送消息。所有流行的视频服务都支持收听这些消息。

点击下面的链接观看现场演示:

https://codepen.io/mcakir/pen/JpQpwm

注意:现场演示会检查视频是否在ViewPort中。我使用的代码块支持来自Youtube,vimeo和dailymotion的播放/暂停iframe视频(更多内容将很快添加),而无需使用任何播放器的库或SDK。

答案 2 :(得分:-2)

getHostName()