Add heap tracking support to YouTube embeds (#19710)

* Add heap tracking support to YouTube embeds

The shortcode has been updated to bootstrap the YouTube API once,
even if there are mutiple embeds on the same page.

Currently supports two events (Video Play and Video Paused) with
attributes for the video id, page path, and page title.

* Update layouts/shortcodes/youtube-embed.html

Co-authored-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>

---------

Co-authored-by: David Karlsson <35727626+dvdksn@users.noreply.github.com>
This commit is contained in:
Michael Irwin 2024-03-29 10:47:20 -04:00 committed by GitHub
parent fc060ddeb9
commit 0ddba23dec
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 56 additions and 7 deletions

View File

@ -1,7 +1,56 @@
<iframe
class="aspect-video w-full"
src="https://www.youtube.com/embed/{{ .Get 0 }}?rel=0"
title="YouTube video player"
frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen></iframe>
<div id="youtube-player-{{ .Get 0 }}" data-video-id="{{ .Get 0}}" class="youtube-video aspect-video w-full"></div>
{{ if page.Scratch.Get "youtube-embed" | default "incomplete" | ne "setup" }}
{{ page.Scratch.Set "youtube-embed" "setup" }}
<script>
(function() {
var tag = document.createElement('script');
tag.id = "youtube-iframe-api";
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubeIframeAPIReady = function() {
var youtubeDivs = document.querySelectorAll(".youtube-video");
for (var i = 0; i < youtubeDivs.length; i++) {
createPlayer(youtubeDivs[i].id, youtubeDivs[i].dataset.videoId);
}
}
function createPlayer(domElementId, videoId) {
new YT.Player(domElementId, {
width: "100%",
height: "100%",
videoId: videoId,
playerVars: {
'rel': 0,
'iv_load_policy': 3,
'enablejsapi': 1,
'origin': window.location.origin
},
events: {
'onStateChange': function (event) {
onPlayerStateChange(event, videoId);
}
}
});
}
function onPlayerStateChange(event, videoId) {
if (window.heap === undefined) return;
var properties = {
video_id: videoId,
page_path: window.location.pathname,
page_title: document.title,
};
if (event.data == YT.PlayerState.PLAYING) {
heap.track("Video Play", properties);
} else if (event.data == YT.PlayerState.PAUSED) {
heap.track("Video Paused", properties);
}
}
})();
</script>
{{ end }}