Last active
September 9, 2024 14:48
-
-
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()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
} | |
} | |
} | |
}); | |
} |
Listening to volume/mute changes: https://codepen.io/zavan/pen/yLavMOw
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 🙏
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
See this live at: https://codepen.io/zavan/pen/PoGQWmG