1. // ==UserScript==
  2. // @name FYTEPlayer: Fast YouTube Embedded Player
  3. // @description Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background. HTML5 direct playback (720p max) is used when selected and available.
  4. // @version 2.0
  5. // @include *
  6. // @exclude https://www.youtube.com/*
  7. // @author wOxxOm
  8. // @namespace wOxxOm.scripts
  9. // @license MIT License
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @grant GM_addStyle
  13. // @grant GM_xmlhttpRequest
  14. // @connect www.youtube.com
  15. // @connect youtube.com
  16. // @run-at document-start
  17. // ==/UserScript==
  18.  
  19. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  20.  
  21. var resizeMode = GM_getValue('resize');
  22. if (typeof resizeMode != 'string') resizeMode = '720p';
  23.  
  24. var resizeWidth = GM_getValue('width', 1280) |0;
  25. var resizeHeight = GM_getValue('height', 720) |0;
  26. updateCustomSize();
  27.  
  28. var playHTML5 = !!GM_getValue('playHTML5', false);
  29. var skipCustom = !!GM_getValue('skipCustom', true);
  30.  
  31. var $ = function(selORnode, sel) { return sel ? selORnode.querySelector(sel) : document.querySelector(selORnode) };
  32. var $$ = function(selORnode, sel) { return sel ? selORnode.querySelectorAll(sel) : document.querySelectorAll(selORnode) };
  33.  
  34. var embedSelector;
  35. initEmbedSelector();
  36.  
  37. processEmbeds($$(embedSelector));
  38.  
  39. document.addEventListener('DOMContentLoaded', function(e) {
  40. adjustNodesIfNeeded(e);
  41. injectStylesIfNeeded();
  42. });
  43.  
  44. window.addEventListener('resize', adjustNodesIfNeeded);
  45.  
  46. var mutQueue = [];
  47. new MutationObserver(function(mutations) {
  48. if (mutations.length == 1) {
  49. // ricing: skip singular mutations with no ELEMENT_NODE added
  50. // (like removal of nodes or creation of TEXT_NODE)
  51. var added = mutations[0].addedNodes;
  52. if (added.length==0 || added.length==1 && added[0].nodeType!=1)
  53. return;
  54. }
  55. mutQueue.push(mutations);
  56. if (mutations.length < 100)
  57. processQueue();
  58. else
  59. setTimeout(processQueue, 0);
  60. }).observe(document, {subtree:true, childList:true});
  61.  
  62. function processQueue() {
  63. while (mutQueue.length) {
  64. var mutationBatch = mutQueue.shift();
  65. for (var m=0, ml=mutationBatch.length, mutation; (m<ml) && (mutation=mutationBatch[m]); m++) {
  66. for (var n=0, nodes=mutation.addedNodes, nl=nodes.length, node; (n<nl) && (node=nodes[n]); n++) {
  67. if (node.nodeType != 1) // skip non-ELEMENT_NODE
  68. continue;
  69. if (node.localName == 'iframe' || node.localName == 'embed') {
  70. if (node.matches(embedSelector))
  71. processEmbeds([node]);
  72. }
  73. else if (node.children.length) {
  74. var embeds = $$(node, embedSelector);
  75. if (embeds.length)
  76. processEmbeds(embeds);
  77. }
  78. }
  79. }
  80. }
  81. }
  82.  
  83. function processEmbeds(nodes) {
  84. for (var i=0, nl=nodes.length, n; i<nl && (n=nodes[i]); i++) {
  85. var np = n.parentNode, npw;
  86. if (!np ||
  87. np.localName == 'object' && !np.parentNode ||
  88. n.className.indexOf('instant-youtube-') >= 0 ||
  89. n.src.indexOf('autoplay=1') > 0 ||
  90. n.onload && getComputedStyle(np).display == 'none' // skip some retarded loaders
  91. )
  92. continue;
  93.  
  94. var id = n.src.match(/(?:embed\/|v[=\/])([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
  95. if (!id)
  96. continue;
  97. id = id[1];
  98.  
  99. var div = document.createElement('div');
  100. div.className = 'instant-youtube-container';
  101. div.srcEmbed = n.src.replace(/&$/, '');
  102. div.videoID = id;
  103.  
  104. div.originalWidth = n.width;
  105. div.originalHeight = n.height;
  106.  
  107. var divSize = calcThumbSize(n);
  108. div.style.maxWidth = divSize.w + 'px';
  109. div.style.height = divSize.h + 'px';
  110.  
  111. var wrapper = div.appendChild(document.createElement('div'));
  112. wrapper.className = 'instant-youtube-wrapper';
  113.  
  114. var img = wrapper.appendChild(document.createElement('img'));
  115. img.className = 'instant-youtube-thumbnail';
  116. img.src = 'https://i.ytimg.com/vi/' + id + '/maxresdefault.jpg';
  117. //img.style.cssText = 'max-width:100%; margin:0 0 0 0;';
  118. img.title = 'Shift-click to use alternative player';
  119. img.onload = function(e) {
  120. var img = e.target;
  121. if (img.naturalWidth <= 120)
  122. return img.onerror(e);
  123. var fitToWidth = true;
  124. if (img.naturalHeight) {
  125. var ratio = img.naturalWidth / img.naturalHeight;
  126. if (ratio > 4.1/3 && ratio < divSize.w/divSize.h) {
  127. img.style.cssText += 'width:auto!important; height:100%!important';
  128. fitToWidth = false;
  129. }
  130. }
  131. if (fitToWidth) {
  132. img.style.cssText += 'width:100%!important; height:auto!important';
  133. }
  134. if (img.videoWidth)
  135. fixThumbnailAR(div);
  136. img.style.setProperty('opacity', '1');
  137. };
  138. img.onerror = function(e) {
  139. var img = e.target;
  140. if (img.src.indexOf('maxresdefault') > 0)
  141. img.src = img.src.replace('maxresdefault','hqdefault');
  142. };
  143.  
  144. GM_xmlhttpRequest({
  145. method: 'GET',
  146. url: div.srcEmbed.replace(/\/(embed\/|v[=\/])/, '/watch?v='),
  147. context: div,
  148. onload: parseWatchPage
  149. });
  150.  
  151. wrapper.insertAdjacentHTML('beforeend', '\
  152. <svg class="instant-youtube-play-button"><path fill-rule="evenodd" clip-rule="evenodd" fill="#1F1F1F" class="ytp-large-play-button-svg" d="M84.15,26.4v6.35c0,2.833-0.15,5.967-0.45,9.4c-0.133,1.7-0.267,3.117-0.4,4.25l-0.15,0.95c-0.167,0.767-0.367,1.517-0.6,2.25c-0.667,2.367-1.533,4.083-2.6,5.15c-1.367,1.4-2.967,2.383-4.8,2.95c-0.633,0.2-1.316,0.333-2.05,0.4c-0.767,0.1-1.3,0.167-1.6,0.2c-4.9,0.367-11.283,0.617-19.15,0.75c-2.434,0.034-4.883,0.067-7.35,0.1h-2.95C38.417,59.117,34.5,59.067,30.3,59c-8.433-0.167-14.05-0.383-16.85-0.65c-0.067-0.033-0.667-0.117-1.8-0.25c-0.9-0.133-1.683-0.283-2.35-0.45c-2.066-0.533-3.783-1.5-5.15-2.9c-1.033-1.067-1.9-2.783-2.6-5.15C1.317,48.867,1.133,48.117,1,47.35L0.8,46.4c-0.133-1.133-0.267-2.55-0.4-4.25C0.133,38.717,0,35.583,0,32.75V26.4c0-2.833,0.133-5.95,0.4-9.35l0.4-4.25c0.167-0.966,0.417-2.05,0.75-3.25c0.7-2.333,1.567-4.033,2.6-5.1c1.367-1.434,2.967-2.434,4.8-3c0.633-0.167,1.333-0.3,2.1-0.4c0.4-0.066,0.917-0.133,1.55-0.2c4.9-0.333,11.283-0.567,19.15-0.7C35.65,0.05,39.083,0,42.05,0L45,0.05c2.467,0,4.933,0.034,7.4,0.1c7.833,0.133,14.2,0.367,19.1,0.7c0.3,0.033,0.833,0.1,1.6,0.2c0.733,0.1,1.417,0.233,2.05,0.4c1.833,0.566,3.434,1.566,4.8,3c1.066,1.066,1.933,2.767,2.6,5.1c0.367,1.2,0.617,2.284,0.75,3.25l0.4,4.25C84,20.45,84.15,23.567,84.15,26.4z M33.3,41.4L56,29.6L33.3,17.75V41.4z"></path><polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" points="33.3,41.4 33.3,17.75 56,29.6"></polygon></svg>\
  153. <span class="instant-youtube-link">' + (playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  154. <div class="instant-youtube-options-button">Options</div>\
  155. ');
  156.  
  157. if (n.parentNode.localName == 'object')
  158. n = n.parentNode;
  159. n.parentNode.insertBefore(div, n);
  160. n.remove();
  161.  
  162. div.addEventListener('click', clickHandler);
  163. }
  164.  
  165. injectStylesIfNeeded();
  166. return true;
  167. }
  168.  
  169. function adjustNodesIfNeeded(e) {
  170. if (resizeMode != 'Original' && !adjustNodesIfNeeded.scheduled)
  171. adjustNodesIfNeeded.scheduled = setTimeout(function() {
  172. adjustNodes(e);
  173. adjustNodesIfNeeded.scheduled = 0;
  174. }, 16);
  175. }
  176.  
  177. function adjustNodes(e, clickedContainer) {
  178. var force = !!clickedContainer;
  179. var nearest = force ? clickedContainer : null;
  180.  
  181. var vids = [].slice.call($$('div.instant-youtube-container'));
  182.  
  183. if (!nearest && e.type != 'DOMContentLoaded') {
  184. var minDistance = window.innerHeight*3/4 |0;
  185. var nearTargetY = window.innerHeight/2;
  186. vids.forEach(function(n) {
  187. var bounds = n.getBoundingClientRect();
  188. var distance = Math.abs((bounds.bottom + bounds.top)/2 - nearTargetY);
  189. if (distance < minDistance) {
  190. minDistance = distance;
  191. nearest = n;
  192. }
  193. });
  194. }
  195.  
  196. if (nearest) {
  197. var bounds = nearest.getBoundingClientRect();
  198. var nearestCenterYpct = (bounds.top + bounds.bottom)/2 / window.innerHeight;
  199. }
  200.  
  201. var resized = false;
  202.  
  203. vids.forEach(function(n) {
  204. var size = calcThumbSize(n);
  205. var w = size.w, h = size.h;
  206.  
  207. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  208. return;
  209.  
  210. if (n.style.maxWidth != w + 'px') n.style.maxWidth = w + 'px';
  211. if (n.style.height != h + 'px') n.style.height = h + 'px';
  212.  
  213. var video = $(n, 'video');
  214. if (video) {
  215. video.width = w;
  216. video.height = h;
  217. }
  218.  
  219. fixThumbnailAR(n);
  220. resized = true;
  221. });
  222.  
  223. if (resized && nearest)
  224. setTimeout(function() {
  225. var bounds = nearest.getBoundingClientRect();
  226. var h = bounds.bottom - bounds.top;
  227. var projectedCenterY = nearestCenterYpct * window.innerHeight;
  228. var projectedTop = projectedCenterY - h/2;
  229. var safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  230. window.scrollBy(0, bounds.top - safeTop);
  231. }, 16);
  232. }
  233.  
  234. function calcThumbSize(node) {
  235. var w, h;
  236. switch (resizeMode) {
  237. case 'Original':
  238. w = node.originalWidth || node.clientWidth;
  239. h = node.originalHeight || node.clientHeight;
  240. break;
  241. case 'Custom':
  242. w = resizeWidth;
  243. h = resizeHeight;
  244. break;
  245. case '1080p':
  246. case '720p':
  247. case '480p':
  248. case '360p':
  249. h = parseInt(resizeMode);
  250. w = Math.round(h / 9 * 16 + 0.49);
  251. break;
  252. default: // fit-to-width mode
  253. do {
  254. node = node.parentElement;
  255. // find parent node with nonzero width (i.e. independent of our video element)
  256. } while (node && !(w = node.clientWidth));
  257. if (w)
  258. h = Math.round(w / 16 * 9 + 0.49);
  259. else {
  260. w = node.clientWidth;
  261. h = node.clientHeight;
  262. }
  263. }
  264. return {w:w, h:h};
  265. }
  266.  
  267. function parseWatchPage(response) {
  268. var div = response.context;
  269. var txt = response.responseText;
  270.  
  271. // parse width & height to adjust the thumbnail
  272. var w = txt.match(/<meta property="og:video:width" content="(\d+)">/);
  273. var h = txt.match(/<meta property="og:video:height" content="(\d+)">/);
  274. if (w && h)
  275. fixThumbnailAR(div, w[1]|0, h[1]|0);
  276.  
  277. // parse video sources
  278. var m = txt.match(/ytplayer\.config\s*=\s*(\{.+?\});\s*ytplayer\.load/);
  279. var videoInfo = [];
  280. if (m) {
  281. var cfg = JSON.parse(m[1]), streams = {};
  282. cfg.args.url_encoded_fmt_stream_map.split(',').forEach(function(stream) {
  283. var params = {};
  284. stream.split('&').forEach(function(kv) {
  285. params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
  286. });
  287. streams[params.itag] = params;
  288. });
  289. cfg.args.fmt_list.split(',').forEach(function(fmt) {
  290. var itag = fmt.split('/')[0];
  291. var dimensions = fmt.split('/')[1];
  292. var stream = streams[itag];
  293. if (stream) {
  294. videoInfo.push({
  295. src: stream.url,
  296. title: stream.quality + ', ' + dimensions + ', ' + stream.type
  297. });
  298. }
  299. });
  300. } else {
  301. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  302. var text = txt.split('url_encoded_fmt_stream_map')[1];
  303. while (m = rx.exec(text)) {
  304. videoInfo.push({
  305. src: decodeURIComponent(decodeURIComponent(m[1]))
  306. });
  307. }
  308. }
  309.  
  310. var title = txt.match(/<title>(.+?)(?:\s*-\s*YouTube)?<\/title>/);
  311. if (title) {
  312. var duration = txt.match(/<meta itemprop="duration" content="\D*(\d+.*?)S?">/);
  313. var a = div.firstElementChild.appendChild(document.createElement('a'));
  314. a.className = 'instant-youtube-persistent-title';
  315. a.innerHTML = '<strong>' + title[1] + '</strong>' +
  316. (duration ? '<span>' + duration[1].replace(/[HM]/, ':0').replace(/\b0(\d\d)/, '$1') + '</span>' : '');
  317. a.href = 'https://www.youtube.com/watch?v=' + div.videoID;
  318. a.target = '_blank';
  319. ['animation', 'webkitAnimation', 'mozAnimation'].some(function(prop) {
  320. if (prop in a.style) {
  321. a.style[prop] = 'instant-youtube-fadein 1s ease-in';
  322. setTimeout(function() { a.style[prop] = '' }, 1000);
  323. return true;
  324. }
  325. });
  326. }
  327.  
  328. if (videoInfo.length)
  329. div.videoInfo = videoInfo;
  330.  
  331. injectStylesIfNeeded();
  332. }
  333.  
  334. function fixThumbnailAR(div, w, h) {
  335. var img = $(div, 'img');
  336. var thw = img.naturalWidth, thh = img.naturalHeight;
  337. if (!thw || !thh) {
  338. // thumbnail is still loading
  339. img.videoWidth = w;
  340. img.videoHeight = h;
  341. return;
  342. } else if (!w || !h) {
  343. w = img.videoWidth;
  344. h = img.videoHeight;
  345. }
  346. var divw = div.clientWidth, divh = div.clientHeight;
  347. // if both video and thumbnail are 4:3, fit the image to height
  348. if (Math.abs(h/w*divw / divh - 1) > 0.05 && Math.abs(thh/thw*divw / divh - 1) > 0.05) {
  349. img.style.cssText = img.style.cssText.replace(/\bheight:.*?;/, 'height:' + img.clientHeight + 'px!important;');
  350. if (!img.videoWidth) // skip animation if thumbnail is already loaded
  351. img.style.transition = 'height 1s ease, margin-top 1s ease';
  352. setTimeout(function() {
  353. img.style.cssText += h/w >= divh/divw ? 'width:auto!important; height:100%!important' : 'width:100%!important; height:auto!important';
  354. setTimeout(function() {
  355. img.style.transition = '';
  356. }, 1000);
  357. }, 0);
  358. }
  359. }
  360.  
  361. function clickHandler(e) {
  362. if (e.target.href)
  363. return;
  364. if (e.target.matches('.instant-youtube-options-button'))
  365. return showOptions(e);
  366. if (e.target.matches('.instant-youtube-options, .instant-youtube-options *'))
  367. return;
  368. div = e.target.closest('.instant-youtube-container');
  369. div.removeEventListener('click', clickHandler);
  370. $(div, 'svg').outerHTML = '<span class="instant-youtube-loading-button"></span>';
  371.  
  372. var alternateMode = e.shiftKey || e.target.className == 'instant-youtube-link';
  373. if (div.videoInfo && (!!playHTML5 + !!alternateMode == 1))
  374. playDirectly(div);
  375. else
  376. switchToIFrame.call(div);
  377. }
  378.  
  379. function playDirectly(div) {
  380. $(div, '.instant-youtube-options-button').style.display = 'none';
  381. $(div, '.instant-youtube-link').style.display = 'none';
  382.  
  383. var video = document.createElement('video');
  384. video.controls = true;
  385. video.autoplay = true;
  386. video.style.cssText = 'width:'+div.clientWidth+'px!important; height:'+div.clientHeight+'px!important;';
  387. video.className = 'instant-youtube-embed';
  388. video.volume = GM_getValue('volume', 0.5);
  389.  
  390. div.videoInfo.forEach(function(src) {
  391. var srcdom = video.appendChild(document.createElement('source'));
  392. Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
  393. srcdom.onerror = switchToIFrame.bind(div);
  394. });
  395.  
  396.  
  397. if (window.chrome) {
  398. video.addEventListener('click', function(e) {
  399. this.paused ? this.play() : this.pause();
  400. });
  401. }
  402. video.interval = (function() {
  403. return setInterval(function() {
  404. if (video.volume != GM_getValue('volume', 0.5))
  405. GM_setValue('volume', video.volume);
  406. }, 1000);
  407. })();
  408. var title = $(div, '.instant-youtube-persistent-title');
  409. if (title) {
  410. video.onpause = function() { title.removeAttribute('hidden') };
  411. video.onplay = function() { title.setAttribute('hidden', true) };
  412. }
  413. video.onloadeddata = function(e) {
  414. pauseOtherVideos(this);
  415. div.firstElementChild.appendChild(this);
  416. this.style.opacity = 1;
  417. var img = $(div, 'img');
  418. img.style.transition = 'opacity 1s';
  419. img.style.opacity = 0;
  420. };
  421. }
  422.  
  423. function switchToIFrame(e) {
  424. var div = this;
  425. var wrapper = div.firstElementChild;
  426. if (e) {
  427. console.log('Direct linking failed on %s, switching to IFRAME player', div.srcEmbed);
  428. var video = e.target ? e.target.closest('video') : e.path && e.path[e.path.length-1];
  429. while (video.lastElementChild)
  430. video.lastElementChild.remove();
  431. }
  432.  
  433. wrapper.insertAdjacentHTML('beforeend',
  434. '<iframe class="instant-youtube-embed" allowtransparency="true" src="' +
  435. div.srcEmbed.replace('http:', 'https:').replace('/v/', '/embed/') +
  436. (div.srcEmbed.indexOf('?') > 0 ? '&' : '?') +
  437. 'html5=1' +
  438. '&autoplay=1' +
  439. '&autohide=2' +
  440. '&border=0' +
  441. '&controls=1' +
  442. '&fs=1' +
  443. '&showinfo=1' +
  444. '&ssl=1' +
  445. '&theme=dark' +
  446. '&enablejsapi=1' +
  447. '" frameborder="0" allowfullscreen width="' + div.clientWidth + '" height="' + div.clientHeight + '"></iframe>');
  448.  
  449. wrapper.lastElementChild.onload = function() {
  450. pauseOtherVideos(this);
  451. this.style.opacity = 1;
  452.  
  453. var div = this.closest('.instant-youtube-container');
  454. div.setAttribute('iframe', '');
  455. setTimeout(function() {
  456. $(div, 'img').style.display = 'none';
  457. var title = $(div, '.instant-youtube-persistent-title');
  458. if (title)
  459. title.remove();
  460. }, 2000);
  461. };
  462. }
  463.  
  464. function pauseOtherVideos(activePlayer) {
  465. [].forEach.call(activePlayer.ownerDocument.getElementsByClassName('instant-youtube-embed'), function(v) {
  466. if (v == activePlayer)
  467. return;
  468. switch (v.localName) {
  469. case 'video':
  470. if (!v.paused)
  471. v.pause();
  472. break;
  473. case 'iframe':
  474. try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {}
  475. break;
  476. }
  477. });
  478. }
  479.  
  480. function showOptions(e) {
  481. var optionsButton = e.target;
  482. optionsButton.insertAdjacentHTML('afterend', '\
  483. <div class="instant-youtube-options">\
  484. <label>Size:<br>\
  485. <select data-action="size-mode">\
  486. <option>Original</option>\
  487. <option>Fit to width</option>\
  488. <option>360p</option>\
  489. <option>480p</option>\
  490. <option>720p</option>\
  491. <option>1080p</option>\
  492. <option value="Custom">Custom...</option>\
  493. </select>\
  494. </label>\
  495. <label data-action="size-custom" ' + (resizeMode != 'Custom' ? 'disabled' : '') + '>\
  496. <input type="number" min="320" max="9999" placeholder="width" step="10" value="' + (resizeWidth||'') + '">\
  497. x\
  498. <input type="number" min="240" max="9999" placeholder="height" step="10" value="' + (resizeHeight||'') + '">\
  499. </label>\
  500. <label title="Tip: shift-clicking thumbnails will use alternative player">\
  501. <input data-action="direct" type="checkbox" ' + (playHTML5 ? 'checked' : '') + '>\
  502. Play directly\
  503. </label>\
  504. <label title="Do not process customized videos with enablejsapi=1 parameter (requires page reload)">\
  505. <input data-action="safe" type="checkbox" ' + (skipCustom ? 'checked' : '') + '>\
  506. Safe\
  507. </label>\
  508. <span data-action="buttons">\
  509. <button>OK</button>\
  510. <button>Cancel</button>\
  511. </span>\
  512. </div>\
  513. ');
  514. var options = optionsButton.nextElementSibling;
  515.  
  516. options.addEventListener('keydown', function(e) {
  517. if (e.target.localName == 'input' &&
  518. !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && e.key.match(/[.,]/))
  519. return false;
  520. });
  521.  
  522. $(options, '[data-action="size-mode"]').value = resizeMode;
  523. $(options, '[data-action="size-mode"]').addEventListener('change', function() {
  524. var v = this.value != 'Custom';
  525. var e = $(options, '[data-action="size-custom"]');
  526. e.children[0].disabled = e.children[1].disabled = v;
  527. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  528. });
  529.  
  530. $(options, '[data-action="buttons"]').addEventListener('click', function(e) {
  531. if (e.target.textContent != 'OK') {
  532. options.remove();
  533. return;
  534. }
  535. var v, shouldAdjust;
  536. if (resizeMode != (v = $(options, '[data-action="size-mode"]').value)) {
  537. GM_setValue('resize', resizeMode = v);
  538. shouldAdjust = true;
  539. }
  540. if (resizeMode == 'Custom') {
  541. var w = $(options, '[placeholder="width"]').value |0;
  542. var h = $(options, '[placeholder="height"]').value |0;
  543. if (resizeWidth != w || resizeHeight != h) {
  544. updateCustomSize(w, h);
  545. GM_setValue('width', resizeWidth);
  546. GM_setValue('height', resizeHeight);
  547. shouldAdjust = true;
  548. }
  549. }
  550. if (playHTML5 != (v = $(options, '[data-action="direct"]').value)) {
  551. GM_setValue('playHTML5', playHTML5 = v);
  552. [].forEach.call($$('.instant-youtube-container .instant-youtube-link'), function(e) {
  553. e.textContent = playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)';
  554. });
  555. }
  556. if (skipCustom != (v = $(options, '[data-action="safe"]').value)) {
  557. GM_setValue('skipCustom', skipCustom = v);
  558. initEmbedSelector();
  559. }
  560.  
  561. options.remove();
  562.  
  563. if (shouldAdjust)
  564. adjustNodes(e, e.target.closest('.instant-youtube-container'));
  565. });
  566. }
  567.  
  568. function updateCustomSize(w, h) {
  569. resizeWidth = Math.min(9999, Math.max(320, w|0 || resizeWidth|0));
  570. resizeHeight = Math.min(9999, Math.max(240, h|0 || resizeHeight|0));
  571. }
  572.  
  573. function initEmbedSelector() {
  574. embedSelector = 'iframe[src*="youtube.com/embed"]~~~, embed[src*="youtube.com/v"]~~~'
  575. .replace(/~~~/g, skipCustom ? ':not([src*="enablejsapi=1"])' : '');
  576. }
  577.  
  578. function injectStylesIfNeeded() {
  579. if (document.head.innerHTML.indexOf('.instant-youtube-container') > 0)
  580. return;
  581. GM_addStyle('\
  582. .instant-youtube-container {contain:strict; position:relative; overflow:hidden; cursor:pointer; background-color:black; padding:0; margin:0; font:normal 14px/1.0 sans-serif,Arial,Helvetica,Verdana; text-align:center}\
  583. .instant-youtube-container .instant-youtube-wrapper {width:100%; height:100%}\
  584. .instant-youtube-container .instant-youtube-thumbnail {transition:opacity 0.1s ease-out; opacity:0; padding:0; margin:auto; position:absolute; left:0; right:0; top:0; bottom:0}\
  585. .instant-youtube-container .instant-youtube-play-button {position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; width:85px; height:60px}\
  586. .instant-youtube-container .instant-youtube-loading-button {position:absolute; left:0; right:0; top:0; bottom:0; padding:0; margin:auto; display:block; width:20px; height:20px; background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==")}\
  587. .instant-youtube-container:hover .ytp-large-play-button-svg {fill:#CC181E}\
  588. .instant-youtube-container .instant-youtube-link, .instant-youtube-container .instant-youtube-link:link, .instant-youtube-container .instant-youtube-link:visited, .instant-youtube-container .instant-youtube-link:active, .instant-youtube-container .instant-youtube-link:focus {\
  589. position:absolute; top:50%; left:0; right:0; width:20em; height:1.7em; margin:60px auto; padding:0; border:none; \
  590. display:block; text-align:center; text-decoration:none; color:white; text-shadow:1px 1px 3px black; font-weight:bold;\
  591. }\
  592. .instant-youtube-container span.instant-youtube-link {font-weight:normal; font-size:12px}\
  593. .instant-youtube-container .instant-youtube-link:hover {color:white; text-decoration:underline; background:transparent}\
  594. .instant-youtube-container .instant-youtube-embed {position:absolute; left:0; top:0; padding:0; margin:0; height:inherit!important; opacity:0; transition:opacity 2s!important}\
  595. .instant-youtube-container iframe {z-index:10}\
  596. .instant-youtube-container .instant-youtube-persistent-title {\
  597. display:block; z-index:9; background-color:rgba(0,0,0,0.5); color:white;\
  598. width:100%; height: 1.9em; top:0; left:0; right:0; position:absolute; z-index: 9;\
  599. color:white; text-shadow:1px 1px 2px black; text-align:center; text-decoration:none;\
  600. margin:0; padding:0.5em 0.5em 0.2em; border:none;\
  601. }\
  602. .instant-youtube-container .instant-youtube-persistent-title strong:after {content:" - watch on Youtube"; font-weight:normal; margin-right:1ex}\
  603. .instant-youtube-container .instant-youtube-persistent-title span {color:inherit}\
  604. .instant-youtube-container .instant-youtube-persistent-title span:before {content:"("}\
  605. .instant-youtube-container .instant-youtube-persistent-title span:after {content:")"}\
  606. @-webkit-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  607. @-moz-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  608. @keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  609. .instant-youtube-container:not(:hover) .instant-youtube-persistent-title[hidden] {display:none; margin:0}\
  610. .instant-youtube-container .instant-youtube-persistent-title:hover {text-decoration:underline}\
  611. .instant-youtube-container .instant-youtube-persistent-title strong {color:white}\
  612. \
  613. .instant-youtube-container .instant-youtube-options-button {position:absolute; right:0; bottom:0; color:white; font-size:11px; text-shadow:1px 1px 2px black; padding:1.5ex 2ex; margin:0; opacity:0.6}\
  614. .instant-youtube-container .instant-youtube-options-button:hover {opacity:1; background:rgba(0,0,0,0.5)}\
  615. \
  616. .instant-youtube-container .instant-youtube-options {position:absolute; right:0; bottom:0; color:white; background:black; padding:2ex 1ex 2ex 2ex; margin:0; opacity:1; display:flex; flex-direction:column; align-items:flex-start; line-height:1.5; text-align:left;}\
  617. .instant-youtube-container .instant-youtube-options * {display:inline; color:white; background:black; font:inherit; font-size:13px; vertical-align:middle; padding:0; margin:0; height:auto; width:auto; text-transform:none; text-align:left; border-radius:0; text-decoration:none;}\
  618. .instant-youtube-container .instant-youtube-options > label {margin-top:1ex}\
  619. .instant-youtube-container .instant-youtube-options select {-webkit-appearance:menulist}\
  620. .instant-youtube-container .instant-youtube-options [data-action="size-custom"] input {width:9ex; border:1px solid #666; padding:.5ex .5ex .4ex;}\
  621. .instant-youtube-container .instant-youtube-options [data-action="buttons"] {margin-top:1em}\
  622. .instant-youtube-container .instant-youtube-options button {padding:.5ex 2ex; margin:0 1ex 0 0; border:2px solid gray; font-weight:bold;}\
  623. .instant-youtube-container .instant-youtube-options button:hover {border-color:white}\
  624. .instant-youtube-container .instant-youtube-options > [disabled] {opacity:0.25}\
  625. ');
  626. }