Skip to content

Instantly share code, notes, and snippets.

@jtallant
Last active January 4, 2016 09:59
Show Gist options
  • Save jtallant/8606033 to your computer and use it in GitHub Desktop.
Save jtallant/8606033 to your computer and use it in GitHub Desktop.
Log YouTube Video Complete to GA

Track YouTube Video Complete to GA

YouTube JS API Docs

<script src="http://www.youtube.com/player_api"></script>
<div class="youtube-player" id="player1" data-videoid="M7lc1UVf-VE"></div>
<div class="youtube-player" id="player2" data-videoid="M7lc1UVf-VE"></div>
function onPlayerReady(event) {
	// uncomment below if you want the video to start playing as soon as it loads
	// you can also add autoplay: 1 to playerVars instead of doing this
    // event.target.playVideo();
}


function onPlayerStateChange(event) {
    console.log(event.data);
    if (YT.PlayerState.ENDED == event.data) {
        console.log('Video end');
        _gaq.push(['_trackEvent', 'video', 'Completed', event.target.getVideoUrl()]);
    }
}


function initYouTubeVideos() {
	var youtubePlayers = $('.youtube-player');

	if (false === youtubePlayers.length > 0) {
		return;
	}

	youtubePlayers.each(function() {
		var player = $(this);
		var playerID = player.attr('id');
		var videoID = player.data('videoid');

		new YT.Player(playerID, {
			height: '390',
			width: '640',
			videoId: videoID,
			// don't show related, this accepts any params an embed would
			// see https://developers.google.com/youtube/player_parameters
			playerVars: {rel: 0},
			events: {
				'onReady': onPlayerReady,
				'onStateChange': onPlayerStateChange
			}
		});
	});
}


function onYouTubePlayerAPIReady() {
	initYouTubeVideos();
}

Example PHP function to extract a YouTube Video ID from a string

/**
 * Attempts to extract a youtube video ID from strings user might input
 */
function get_youtube_vid_id($link) {

    $delimiters = array(
        'watch?v=',
        'youtu.be/',
        'embed/',
        'youtube.com/v/'
    );

    $vid_id = false;

    foreach ($delimiters as $delimiter) {
        if (false !== stripos($link, $delimiter)) {
            $link = explode($delimiter, $link);

            # Remove any params coming after "v"
            if (false !== strpos($link[1], '&')) {
                $params = explode('&', $link[1]);
                $vid_id = $params[0];
            } else {
                $vid_id = $link[1];
            }

            break;
        }
    }

    if ($vid_id) {
        return $vid_id;
    }

    return '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment