LoginSignup
80
79

More than 5 years have passed since last update.

【JS】YouTubeのiframe埋め込み動画をJSでコントロール

Last updated at Posted at 2015-09-01

YouTubeの埋め込みコードで動画をWebサイトに埋め込むことが出来ますが、再生や停止をJSでコントロールしたい場合があり、調べてみました。

ちなみにYouTubeはie8のサポートはもうしていないみたいです。ie8でYouTubeにアクセスすると以下のような画面になります。

スクリーンショット 2015-09-01 10.22.54.png

実装

Sample Page

HTML

HTMLでポイントなのは、iframeのsrcにenablejsapi=1というパラメーターを付加することです。
enablejsapiに1を設定することでプレーヤーJavaScript APIが有効になります。

その他のパラメーターはこちらを参照 → YouTube IFrame API Parameters

index.html
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <title>Document</title>
</head>
<body>
  <iframe class="video" id="popup-YouTube-player" width="560" height="315" src="https://www.YouTube.com/embed/13S9kfvkchA?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
  <button id="play">play</button>
  <button id="pause">pause</button>
  <button id="stop">stop</button>
  <button id="clear">clear</button>
</body>
</html>

JS(jQuery)

JSでは、iframeのwindowにpostMessageでイベントを渡してあげるだけです。
これだけで、再生、停止、ストップをコントロールすることができます。
クリアはなんか上手くいかなかった。。

YouTube IFrame API 再生の制御

script.js
$(function(){
  $("#play").on("click", function(){
  videoControl("playVideo"); 
  });

  $("#pause").on("click", function(){
    videoControl("pauseVideo");
  });

  $("#stop").on("click", function(){
    videoControl("stopVideo");
  });

  $("#clear").on("click", function(){
    videoControl("clearVideo");
  });

  function videoControl(action){ 
    var $playerWindow = $('#popup-YouTube-player')[0].contentWindow;
    $playerWindow.postMessage('{"event":"command","func":"'+action+'","args":""}', '*');
  }
});

postMessageの参考

80
79
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
80
79