Skip to content

Instantly share code, notes, and snippets.

@FirstWhack
Created March 3, 2015 22:41
Show Gist options
  • Save FirstWhack/99eeb664ee835cb3ebea to your computer and use it in GitHub Desktop.
Save FirstWhack/99eeb664ee835cb3ebea to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Stackexchange HTML 5 Youtube Enabler
// @namespace http://your.homepage/
// @version 0.1
// @description Replaces embed tags with iFrames and uses the Youtube Iframe API
// @author jhawins
// @include http://*stackexchange.com/questions/*
// @include http://*stackoverflow.com/questions/*
// @grant none
// ==/UserScript==
(function(){
var embeds = document.getElementsByTagName("embed");
var tubeOpts = {}, toBeTubed = {};
// check for youtube links
for (var i = 0; i < embeds.length; i++) {
if (embeds[i].src.indexOf("youtube") > -1) {
tubeOpts = {
'videoId': youtube_parser(embeds[i].src),
'width': embeds[i].width,
'height': embeds[i].height
};
toBeTubed[i] = {
options: tubeOpts,
oldTube: embeds[i]
}
}
}
// check if there were any videos to convert
if (Object.keys(toBeTubed).length > 0) createIframes(toBeTubed);
function createIframes(newtubes) {
window.onYouTubeIframeAPIReady = function() {
for (var k in newtubes) {
player = new YT.Player(newtubes[k].oldTube, {
width: newtubes[k].options.width,
height: newtubes[k].options.height,
videoId: newtubes[k].options.videoId,
playerVars: {
html5: 1
},
events: {
'onError': function(err) {
console.log(err);
}
}
});
}
}
// Add Youtube iFrame API
var tag = document.createElement('script');
tag.id = "YTIframeAPI";
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
function youtube_parser(url) {
var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[7].length == 11) {
return match[7];
} else {
return false;
}
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment