YouTube API: List and play videos

  1. Authentication and initialization
  2. Get channel
  3. Get playlist items
  4. Playback
  5. The HTML

Authentication and initialization

/* To get your own keys, create a project at https://console.developers.google.com
and navigate to APIs & auth > Credentials */
var OAUTH2_CLIENT_ID = "_YOUR_CLIENT_ID_",
		OAUTH2_SCOPES = ["https://www.googleapis.com/auth/youtube"];

function googleApiClientReady() {
	"use strict";

	var el;

	// Your public API key
	gapi.client.setApiKey("_YOUR_API_KEY_");

	gapi.client.load("youtube", "v3", function() {

		document.getElementById("results").addEventListener("click", resultControls, false);

		el = document.getElementById("getVideos");
		el.removeAttribute("disabled");
		el.addEventListener("click", function() {
			var channelId = document.getElementById("channelId").value;
			if (channelId) {
				getChannel({
					part: "contentDetails",
					id: channelId
				});
			}
		}, false);
	});

	gapi.auth.init(function() {
		window.setTimeout(checkAuth, 1);
	});
}

function checkAuth(immediate) {
	"use strict";

	gapi.auth.authorize({
		client_id: OAUTH2_CLIENT_ID,
		scope: OAUTH2_SCOPES,
		immediate: (immediate !== false ? true : false),
	}, handleAuthResult);
}

function handleAuthResult(authResult) {
	"use strict";

	var el;

	if (authResult && !authResult.error) {
		document.getElementById("loginButton").setAttribute("disabled", "disabled");

		el = document.getElementById("getMyVideos");
		el.removeAttribute("disabled");
		el.addEventListener("click", function() {
			// Authenticated user's channel
			getChannel({
				part: "contentDetails",
				mine: true
			});
		}, false);
	}
	else {
		document.getElementById("loginButton").onclick = function() {
			checkAuth(false);
		};
	}
}

Get channel

function getChannel(params) {
	"use strict";

	gapi.client.youtube.channels.list(params).execute(function(response) {
		if (response.error) {
			alert("Error: " + response.error.message);
		}
		else {
			getPlaylistItems({
				playlistId: response.items[0].contentDetails.relatedPlaylists.uploads,
				part: "snippet"
			});
		}
	});
}

Get playlist items

function getPlaylistItems(params) {
	"use strict";

	var container = document.getElementById("results"),
			items,
			item,
			i,
			obj;

	container.innerHTML = "";

	gapi.client.youtube.playlistItems.list(params).execute(function(response) {
		if (response.error) {
			alert("Error: " + response.error.message);
		}
		else if (response.pageInfo.totalResults === 0) {
			container.appendChild(document.createTextNode("No results."));
		}
		else if (response.pageInfo.totalResults > 0) {
			container.appendChild(document.importNode(document.getElementById("items").content, true));
			items = container.querySelector(".items");

			if (response.nextPageToken) {
				params.pageToken = response.nextPageToken;
				container.querySelector(".more").removeAttribute("disabled");
				container.querySelector(".more").addEventListener("click", function click(e) {
					e.target.removeEventListener("click", click, false);
					getPlaylistItems(params);
				}, false);
			}

			for (i = 0; i < response.items.length; i += 1) {
				obj = response.items[i];
				item = document.importNode(document.getElementById("video").content, true);
				item.querySelector(".item").setAttribute("data-id", obj.snippet.resourceId.videoId);
				item.querySelector("img").setAttribute("src", obj.snippet.thumbnails["default"].url);
				item.querySelector(".title").appendChild(document.createTextNode(obj.snippet.title));
				items.appendChild(item);
			}
		}
	});
}

Playback

function resultControls(e) {
	"use strict";

	var el;

	// unnecessary at this point, but because we have fake buttons, we'll restrict the action to them
	if (e.target.nodeName !== "BUTTON") {
		return;
	}

	el = e.target;

	while (el && el.id !== "results" && !el.getAttribute("data-id")) {
		el = el.parentNode;
	}

	if (el.getAttribute("data-id")) {
		document.getElementById("videoPlayer").setAttribute("src", "http://www.youtube.com/embed/" + el.getAttribute("data-id") + "?autoplay=1&html5=1");
	}
}

The HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>YouTube Data API Demo</title>
<style>
	hidden {display:none}
	hr {margin:1em 0; border-width:1px 0px 0px 0px; border-style:dashed; border-color:black}
	iframe {display:block; background-color:#ddd; border:none}
	img {max-width:150px}
</style>
<script src="youtube-getvideos.js"></script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</head>
<body>

<button id="loginButton" type="button">Sign in</button>

<hr>

<input id="channelId" type="text" value="UCSOkex4abVl14cZ4tLyUYzw"> <button id="getVideos" type="button" disabled>Get videos by channel ID</button>

<hr>

<button id="getMyVideos" type="button" disabled>My videos</button>

<hr>

<div id="results"></div>

<hr>

<iframe id="videoPlayer" width="640" height="390"></iframe>

<template id="items" hidden>
	<ul class="items"></ul>
	<button class="more" type="button" disabled>More results</button>
</template>
<template id="video" hidden>
	<li class="item" data-kind="video">
		<img>
		<span class="title"></span>
		<button type="button">Play</button>
	</li>
</template>

</body>
</html>
Using
  • YouTube Data API v3
  • Javascript client library

Comments