目次
YouTube動画をコントロールしたい
YouTubeの動画をダイアログボックスで表示した時にYouTubeを再生したままダイアログボックスを閉じたら再生されっぱなしに…ダイアログボックスを閉じた時に再生を止めたかったのでJavaScriptで閉じるイベントが発生した際に再生を止める処理を行いたかったので、その対応方法をメモ。
YouTubeのURLにパラメータを設定
YouTubeのAPIを利用してコントロールするのですが、まずはYouTubeのAPIを有効にする必要があります。そこでYouTubeのiframe要素のsrc属性に設定されているYouTubeのURLにenablejsapi=1
というパラメータを設定します。
<iframe width="560" height="315" src="https://www.youtube.com/embed/XpPXHEvCRAI?enablejsapi=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
再生・一時停止・停止ボタンを準備
次にJavaScriptでイベントを発生するためのボタンを準備しておきます。id属性を設定してそれぞれのボタンに任意の値を設定。
<button id="play">play</button>
<button id="pause">pause</button>
<button id="stop">stop</button>
postMessageで送信
最後にWindow.postMessage()
で、YouTubeのIFrame Player APIにメッセージ(データ)を送信します。それぞれのボタンにクリックイベントを設定して自作のcontrolVideo
関数にメッセージを渡して実行。
let
youtube = document.querySelector('iframe').contentWindow,
play = document.getElementById('play'),
pause = document.getElementById('pause'),
stop = document.getElementById('stop');
const controlVideo = (func) => {
let message = '{"event": "command", "func": "' + func + '", "args": ""}';
youtube.postMessage(message, '*');
};
play.addEventListener('click', () => {
controlVideo('playVideo');
});
pause.addEventListener('click', () => {
controlVideo('pauseVideo');
});
stop.addEventListener('click', () => {
controlVideo('stopVideo');
});
できた!\(^o^)/
今回は単純な操作のみの制御だったけど、リファレンスにはもっと細かく設定できる内容が書かれていたので試してみたい。
参考サイト
- IFrame Player API
- https://developers.google.com/youtube/iframe_api_reference?hl=ja
- YouTube 埋め込みプレーヤーとプレーヤーのパラメータ
- https://developers.google.com/youtube/player_parameters?hl=ja