The YouTube IFrame Player API doesn't expose any way to listen for time change updates, but since internally it uses postMessage
events to communicate between the IFrame and the main window, you can add a listener to your window to listen to them and react only to the time change ones:
// Instantiate the Player.
function onYouTubeIframeAPIReady() {
var player = new YT.Player("player", {
height: "390",
width: "640",
videoId: "dQw4w9WgXcQ"
});
// 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.
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.
}
}
}
});
}
See it live.
Note that this relies on a private API that may change at anytime without previous notice.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…