Skip to content

Instantly share code, notes, and snippets.

Last active Dec 30, 2020
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 = "";
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:
window.addEventListener("message", function(event) {
// Check that the event was sent from the YouTube IFrame.
if (event.source === iframeWindow) {
var data = JSON.parse(;
// 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" && &&
) {
// currentTime is emitted very frequently,
// but we only care about whole second changes.
var time = Math.floor(;
if (time !== lastTimeUpdate) {
lastTimeUpdate = time;
console.log(time); // Update the dom, emit an event, whatever.
Copy link

zavan commented Dec 30, 2020

Copy link

zavan commented Dec 30, 2020

Listening to volume/mute changes:

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