Matomo supports tracking YouTube media through the Media Analytics plugin. However, tracking YouTube events requires using the YouTube tracker JS, which generates a cookie. This can lead to compliance issues under privacy regulations like GDPR.

To address this, you can configure tracking to begin only after user consent by following the steps below, or use another video player that does not set cookies without consent.

Insert the following script before the Matomo JS tracking code to temporarily disable YouTube tracking:

<script>
window.matomoMediaAnalyticsAsyncInit = function () {
    window.__Matomo_YT_player = null;
    if (window.Matomo && window.Matomo.MediaAnalytics) {
        // Disable media tracking
        window.Matomo.MediaAnalytics.disableMediaAnalytics();

        // Copy the YouTube player to a global variable
        window.__Matomo_YT_player = window.Matomo.MediaAnalytics.players.getPlayer('youtube');

        // Remove the YouTube player to prevent tracking
        window.Matomo.MediaAnalytics.players.removePlayer('youtube');

        // Re-enable media tracking for other players
        window.Matomo.MediaAnalytics.enableMediaAnalytics();
        window.Matomo.MediaAnalytics.scanForMedia();
    }
};
</script>

After obtaining user consent, enable the YouTube player and rescan for media with the following code:

<script>
if (window.__Matomo_YT_player && window.Matomo && window.Matomo.MediaAnalytics) {
    // Register the YouTube player after consent and re-scan for media
    window.Matomo.MediaAnalytics.players.registerPlayer('youtube', window.__Matomo_YT_player);
    window.Matomo.MediaAnalytics.scanForMedia();
}
</script>

This approach ensures YouTube tracking is reinstated in compliance with visitor consent, enabling responsible data collection while adhering to privacy regulations.

Previous FAQ: How do I prevent YouTube from placing cookies when tracking YouTube videos?