Skip to content

Instantly share code, notes, and snippets.

@zavan
Last active Dec 30, 2020
Embed
What would you like to do?
Listening to the YouTube Embed Iframe time change events without polling player.getCurrentTime()
// Load the IFrame Player API code asynchronously.
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Instantiate the Player.
function onYouTubeIframeAPIReady() {
var player = new YT.Player("player", {
height: "390",
width: "640",
videoId: "M7lc1UVf-VE"
});
// This is the source "window" that will emit the events.
var iframeWindow = player.getIframe().contentWindow;
// So we can compare against new updates.
var lastTimeUpdate = 0;
// Listen to events triggered by postMessage,
// this is how different windows in a browser
// (such as a popup or iFrame) can communicate.
// See: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
window.addEventListener("message", function(event) {
// Check that the event was sent from the YouTube IFrame.
if (event.source === iframeWindow) {
var data = JSON.parse(event.data);
// The "infoDelivery" event is used by YT to transmit any
// kind of information change in the player,
// such as the current time or a playback quality change.
if (
data.event === "infoDelivery" &&
data.info &&
data.info.currentTime
) {
// currentTime is emitted very frequently,
// but we only care about whole second changes.
var time = Math.floor(data.info.currentTime);
if (time !== lastTimeUpdate) {
lastTimeUpdate = time;
console.log(time); // Update the dom, emit an event, whatever.
}
}
}
});
}
@zavan
Copy link
Author

zavan commented Dec 30, 2020

@zavan
Copy link
Author

zavan commented Dec 30, 2020

Listening to volume/mute changes: https://codepen.io/zavan/pen/yLavMOw

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment