To detect when a YouTube video finishes playing with JavaScript, we can set the events.onReady
and events.onStateChange
methods in the object we pass into the YT.Player
constructor.
For instance, we can write the following HTML:
<div id="player"></div>
Then we can add a video into the div with the YouTube API by writing:
const tag = document.createElement("script");
tag.id = "iframe-demo";
tag.src = "https://www.youtube.com/iframe_api";
const [firstScriptTag] = document.getElementsByTagName("script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
let player;
window.onPlayerReady = (event) => {
event.target.playVideo();
};
window.onPlayerStateChange = (event) => {
if (event.data === 0) {
console.log("done");
}
};
window.onYouTubeIframeAPIReady = () => {
player = new window.YT.Player("player", {
width: 200,
height: 100,
videoId: "M7lc1UVf-VE",
events: {
onReady: window.onPlayerReady,
onStateChange: window.onPlayerStateChange
}
});
};
We add the YouTube script with:
const tag = document.createElement("script");
tag.id = "iframe-demo";
tag.src = "https://www.youtube.com/iframe_api";
const [firstScriptTag] = document.getElementsByTagName("script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
Then we add the onPlayerReady
method with:
window.onPlayerReady = (event) => {
event.target.playVideo();
};
to play the video when the player is ready.
Then we have the onPlayerStateChange
method that checks if event.data
is 0.
If it is, then we know the video is done playing.
And finally, we have the onYouTubeIframeAPIReady
method to create a YouTube player with the YT.Player
constructor.
'player'
is the ID of the div that houses the video.
width
and height
are the width and height.
videoId
is the ID of the YouTube video to play.
And the events
property have the event listeners for when the video player is ready and when the video player state changes, which are onReady
and onStateChange
respectively.