Skip to content

Instantly share code, notes, and snippets.

@hanachin
Forked from tompng/gist:3719273
Created September 14, 2012 01:46
Show Gist options
  • Save hanachin/3719324 to your computer and use it in GitHub Desktop.
Save hanachin/3719324 to your computer and use it in GitHub Desktop.
youtube gen playlist
(function () {
var script = document.createElement("script");
script.src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js";
document.body.appendChild(script);
function youtubeUrls(html) {
return html.match(/http:\/\/www.youtube.com\/embed\/[a-zA-Z0-9]+/g) || [];
}
function youtubeVideoId(url) {
return url.match(/[a-zA-Z0-9]+$/)[0];
}
function playVideos(video_ids_src) {
var video_ids = video_ids_src.slice(0);
var first_video_id = video_ids.pop();
var onYouTubePlayerReady = function (player_id) {
var player = document.getElementById(player_id);
var onYouTubePlayerStateChange = function(state) {
/* state 0 is play ended */
if (state == 0) {
player.loadVideoById(video_ids.pop());
}
};
window.onYouTubePlayerStateChange = onYouTubePlayerStateChange;
player.addEventListener("onStateChange", "onYouTubePlayerStateChange");
};
window.onYouTubePlayerReady = onYouTubePlayerReady;
var embed_url = "http://www.youtube.com/v/" + first_video_id + "?enablejsapi=1&autoplay=1&playerapiid=player";
document.body.innerHTML = '<div id="container"></div>';
swfobject.embedSWF(embed_url, "container", "854", "480", "8", null, null, { allowScriptAccess: "always" }, { id: "player" });
}
function wait_swfobject(callback) {
var interval_id = setInterval(function () {
if (!swfobject) return;
clearInterval(interval_id);
callback();
}, 10);
}
wait_swfobject(function () {
var html = document.body.innerHTML;
var youtube_video_ids = youtubeUrls(html).map(youtubeVideoId);
playVideos(youtube_video_ids);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment