Skip to content

Instantly share code, notes, and snippets.

@Kugelschieber
Last active December 2, 2023 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kugelschieber/0f2912151d53e78cbb04ec637a8da183 to your computer and use it in GitHub Desktop.
Save Kugelschieber/0f2912151d53e78cbb04ec637a8da183 to your computer and use it in GitHub Desktop.
Pirsch YouTube Video Tracking Demo
<!DOCTYPE html>
<html>
<head>
<title>YouTube Pirsch Demo</title>
<!-- Add the Pirsch extended script to support page views and events. -->
<script defer src="https://api.pirsch.io/pirsch-extended.js"
id="pirschextendedjs"
data-code="YOUR_PIRSCH_CODE"></script>
<!-- Add the YouTube iframe API script. -->
<script src="https://www.youtube.com/iframe_api"></script>
</head>
<body>
<div id="player"></div>
<script>
// Initialize the player and set up an event handler for state changes.
// The progress will be tracked as a number between 0 and 100%.
let player;
let progress = 0;
function onYouTubeIframeAPIReady() {
player = new YT.Player("player", {
height: "360",
width: "640",
videoId: "dQw4w9WgXcQ",
events: {
"onStateChange": (event) => {
if (event.data === YT.PlayerState.PAUSED || event.data === YT.PlayerState.ENDED) {
progress = Math.round(player.getCurrentTime() / player.getDuration() * 100);
console.log(progress); // debugging
}
}
}
});
}
// Send the progress when the page is navigated away from or the tab/window is closed.
window.addEventListener("beforeunload", () => {
pirsch("YT Video Playback", {
meta: {
progress
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment