要利用 javascript 控制 Youtube 影片,使其暫停或停止,可以參考以下方法,首先嵌入影片的 code 類似這樣:
<iframe width="560" height="315" id="YTVideo" src="https://www.youtube.com/embed/QM_vdeG9vpQ?enablejsapi=1" ></iframe>
注意我有加上 id 是要抓取目標用,另外在網址後面我加上了 ?enablejsapi=1 是允許可以讓 javascript 控制 Youtube 影片,接著準備控制的 html:
<button id="pause">pause</button> <button id="stop">top</button>
各自綁定事件:
const pauseBtn=getElementById("pause");
const stopBtn=getElementById("stop");
const video = document.getElementById("YTVideo")
//暫停
pauseBtn.addEventListener("click", function(){
video.contentWindow.postMessage( '{"event":"command", "func":"pauseVideo", "args":""}', '*');
})
//停止
stopBtn.addEventListener("click", function(){
video.contentWindow.postMessage( '{"event":"command", "func":"stopVideo", "args":""}', '*');
})
透過點擊後把事件傳進 iframe 即可。
參考:
How can I stop a video with JavaScript in Youtube?