How can I collect data about YouTube videos on my site? (custom code)

Tag Manager

Analytics

Note: This method is only for accounts with versions below 16.5.0. For version 16.5.0 and higher, use the YouTube video tracking tag.

When you want to track YouTube videos embedded on your site, you need to set up custom tracking in Tag Manager. In this article, we’ll show you how to do it.

To set up YouTube video tracking, follow these steps:

  1. Here’s the code that you’ll use:
    <script type="text/javascript">
      !function(e, t, a) {for (var i = e.getElementsByTagName("iframe"), r = i.length; r--;) /youtube.*\/embed/.test(i[r].src) && -1 === i[r].src.indexOf("enablejsapi=") && (i[r].src += (-1 === i[r].src.indexOf("?") ? "?" : "&") + "enablejsapi=1");var n = [];function o(e) {return (e.getCurrentTime() / e.getDuration() * 100).toFixed()}function g(e, t, a) {var i = e.getVideoData();a = a || i.video_id + ":" + i.title, dataLayer.push({ event: "youtube", action: t, label: a, video_id: i.video_id, video_title: i.title, position: e.getCurrentTime().toFixed(), total_length: e.getDuration().toFixed(), percentage: o(e), video_player: "youtube", type: "video" })}function s(e) {e.data == YT.PlayerState.PLAYING && setTimeout(c, 1e3, e.target), e.data == YT.PlayerState.PLAYING && (["i", "p"].indexOf(YT.gtmLastAction) > -1 && g(e.target, "i" == YT.gtmLastAction ? "play" : "resume"), YT.gtmLastAction = ""), e.data == YT.PlayerState.PAUSED && (g(e.target, "pause"), YT.gtmLastAction = "p"), e.data === YT.PlayerState.ENDED && (g(e.target, "complete"), YT.gtmLastAction = "i")}function u(e) {g(e, "error", "youtube:" + e)}function c(e) {if (e.getPlayerState() == YT.PlayerState.PLAYING) {var t, i = a.percentageTracking || [25, 50, 75], r = e.lastP || -1, n = i[i.length - 1] || -1;for (t = 0; t < i.length; t += 1) if (i[t] > r) {r = i[t];break} if (r > -1) {var s = o(e), u = s >= n;s >= r && (e.lastP = u ? 200 : s, g(e, r + "%")), u || setTimeout(c, 1e3, e)}}}t.onYouTubeIframeAPIReady = function() {for (var t = e.getElementsByTagName("iframe"), a = t.length; a--;) /youtube.*\/embed/.test(t[a].src) && (n.push(new YT.Player(t[a], { events: { onStateChange: s, onError: u } })), YT.gtmLastAction = "i")};var l = e.createElement("script"), d = e.getElementsByTagName("script")[0];l.src = "//www.youtube.com/iframe_api", l.async = !0, d.parentNode.insertBefore(l, d)}
    
      (document, window, {
        percentageTracking: [25, 50, 75]
      });
    </script>

    In this code, you can change the following parameters:

    • percentageTracking: [25, 50, 75]: The percentage of watched video. You can change the values or don’t use this element at all.

    This code also contains the following elements that can be used in the custom event:

    • Type: video
    • Video_player: youtube
    • Action: A user takes one of the following cations: play, pause, resume, complete, and the progress of the played video based on percentageTracking settings.
    • Video_id: The video ID in YouTube, for example OZJOIwm4y1c.
    • Video_title: The video title in YouTube.
    • Position: The progress of the played video in seconds, counted from the beginning.
    • Percentage: A user reaches a percentage threshold in their watch time. By default, the thresholds are: 25%, 50%, 75%. You can change thresholds by using percentageTracking option.
    • Total_length: Video length in seconds, counted from the beginning.
  2. Go to Menu > Tag Manager.
  3. Navigate to Tags.
  4. Click Add a tag.
  5. Name your tag and choose the following type: Custom code (async) tag.
  6. Click Next.
  7. In Tag code, paste the code from step 1.
    Tag for tracking YouTube videos in Piwik PRO
  8. In Advanced tag settings > Consent type, select the following type: Analytics.
    Consent type in Tag Manager in Piwik PRO

    Note: Set it up if you use a consent form on your site. This tag will only fire for visitors who accept the selected consent type.

  9. In Tag triggers, click Choose existing trigger.
  10. Select All page views and click Save.
  11. Click Save to save the tag.
  12. Click Add a tag.
  13. Name the tag and select the following type: Piwik PRO custom event.
  14. In Piwik PRO custom event setup, set the following:
    • Category: {{ type }}
    • Action: {{ action }}
    • Name: {{ video_title }}
    • Value (optional): {{ percentage }} or {{ position }} or other value
    Set up for tracking YouTube videos in Piwik PRO
  15. In Custom dimensions, you can optionally assign dimension values to dimension IDs.
    Set up for tracking YouTube videos in Piwik PRO

    Note: Before assigning any dimension value, you need to create a custom dimension under Analytics > Settings > Custom dimensions.

  16.  In Tag triggers, click Add new trigger.
  17.  Name the trigger. For example, YouTube event.
  18. Choose the following type: Data layer event.
  19.  In Data layer event settings, set the following condition: Event name equals youtube.
    Set up for tracking YouTube videos in Piwik PRO
  20. Click OK to finish creating the trigger.
  21. Click OK to finish creating the tag.
  22. Test your tags in debug mode.
  23. When you’re happy how the tags work, click Publish.
  24. Done! Now Piwik PRO will be tracking events on YouTube videos embedded on your website. You’ll be able to see tracked data in the custom event report and session log report.

Was this article helpful?

Technical support

If you still have any questions, visit our community.
There’s always someone happy to help!

Back to help center