Skip to content

Instantly share code, notes, and snippets.

@zavan
Last active July 16, 2025 19:53
Show Gist options
  • Select an option

  • Save zavan/75ed641de5afb1296dbc02185ebf1ea0 to your computer and use it in GitHub Desktop.

Select an option

Save zavan/75ed641de5afb1296dbc02185ebf1ea0 to your computer and use it in GitHub Desktop.
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
Copy Markdown
Author

zavan commented Dec 30, 2020

@zavan
Copy link
Copy Markdown
Author

zavan commented Dec 30, 2020

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

@wc2184
Copy link
Copy Markdown

wc2184 commented Oct 20, 2022

This is awesome dude, using this extensively for my current Spotify clone project that fetches audio from YouTube music videos in a iframe project. Thank you ๐Ÿ™

@MBilalMuscled
Copy link
Copy Markdown

MBilalMuscled commented Dec 29, 2022

Awesome Man! Can we use this event for setting up player properties as well ?

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