FYTE /Fast YouTube Embedded/ Player

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.

当前为 2016-07-11 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name FYTE /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.2
  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. // @require https://greasyfork.org/scripts/12228/code/setMutationHandler.js
  18. // ==/UserScript==
  19.  
  20. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  21.  
  22. var resizeMode = GM_getValue('resize', 'Fit to width');
  23. if (typeof resizeMode != 'string')
  24. resizeMode = resizeMode ? 'Fit to width' : 'Original';
  25.  
  26. var resizeWidth = GM_getValue('width', 1280) |0;
  27. var resizeHeight = GM_getValue('height', 720) |0;
  28. updateCustomSize();
  29.  
  30. var playHTML5 = !!GM_getValue('playHTML5', false);
  31. var skipCustom = !!GM_getValue('skipCustom', true);
  32.  
  33. var $ = function(selORnode, sel) { return sel ? selORnode.querySelector(sel) : document.querySelector(selORnode) };
  34. var $$ = function(selORnode, sel) { return Array.prototype.slice.call(sel ? selORnode.querySelectorAll(sel) : document.querySelectorAll(selORnode)) };
  35.  
  36. var embedSelector = 'iframe[src*="youtube.com/embed"], embed[src*="youtube.com/v"]';
  37.  
  38. document.addEventListener('DOMContentLoaded', function(e) {
  39. adjustNodesIfNeeded(e);
  40. injectStylesIfNeeded();
  41. });
  42.  
  43. window.addEventListener('resize', adjustNodesIfNeeded);
  44.  
  45. processEmbeds($$(embedSelector));
  46. setMutationHandler(document, embedSelector, processEmbeds);
  47.  
  48. function processEmbeds(nodes) {
  49. for (var i=0, nl=nodes.length, n; i<nl && (n=nodes[i]); i++) {
  50. var np = n.parentNode, npw;
  51. if (!np ||
  52. skipCustom && n.src.indexOf('enablejsapi=1') > 0 ||
  53. np.localName == 'object' && !np.parentNode ||
  54. n.className.indexOf('instant-youtube-') >= 0 ||
  55. n.src.indexOf('autoplay=1') > 0 ||
  56. n.onload && getComputedStyle(np).display == 'none' // skip some retarded loaders
  57. )
  58. continue;
  59.  
  60. var id = n.src.match(/(?:embed\/|v[=\/])([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
  61. if (!id)
  62. continue;
  63. id = id[1];
  64.  
  65. var div = document.createElement('div');
  66. div.className = 'instant-youtube-container';
  67. div.FYTE = {
  68. state: 'querying',
  69. srcEmbed: n.src.replace(/&$/, ''),
  70. videoID: id,
  71. originalWidth: n.width|0 || n.clientWidth,
  72. originalHeight: n.height|0 || n.clientHeight,
  73. };
  74.  
  75. var divSize = calcThumbSize(n);
  76. div.style.maxWidth = divSize.w + 'px';
  77. div.style.height = divSize.h + 'px';
  78.  
  79. var wrapper = div.appendChild(document.createElement('div'));
  80. wrapper.className = 'instant-youtube-wrapper';
  81.  
  82. var img = wrapper.appendChild(document.createElement('img'));
  83. img.className = 'instant-youtube-thumbnail';
  84. img.src = 'https://i.ytimg.com/vi/' + id + '/maxresdefault.jpg';
  85. img.style.cssText = important('transition:opacity 0.1s ease-out; opacity:0; padding:0; margin:auto; position:absolute; left:0; right:0; top:0; bottom:0;');
  86.  
  87. img.title = 'Shift-click to use alternative player';
  88. img.onload = function(e) {
  89. var img = e.target;
  90. if (img.naturalWidth <= 120)
  91. return img.onerror(e);
  92. var fitToWidth = true;
  93. if (img.naturalHeight) {
  94. var ratio = img.naturalWidth / img.naturalHeight;
  95. if (ratio > 4.1/3 && ratio < divSize.w/divSize.h) {
  96. img.style.cssText += important('width:auto; height:100%;');
  97. fitToWidth = false;
  98. }
  99. }
  100. if (fitToWidth) {
  101. img.style.cssText += important('width:100%; height:auto;');
  102. }
  103. if (img.videoWidth)
  104. fixThumbnailAR(div);
  105. img.style.opacity = 1;
  106. };
  107. img.onerror = function(e) {
  108. var img = e.target;
  109. if (img.src.indexOf('maxresdefault') > 0)
  110. img.src = img.src.replace('maxresdefault','hqdefault');
  111. };
  112.  
  113. GM_xmlhttpRequest({
  114. method: 'GET',
  115. url: div.FYTE.srcEmbed.replace(/\/(embed\/|v[=\/])/, '/watch?v='),
  116. context: div,
  117. onload: parseWatchPage
  118. });
  119.  
  120. wrapper.insertAdjacentHTML('beforeend', '\
  121. <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>\
  122. <span class="instant-youtube-link">' + (playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  123. <div class="instant-youtube-options-button">Options</div>\
  124. ');
  125.  
  126. if (n.parentNode.localName == 'object')
  127. n = n.parentNode;
  128. n.parentNode.insertBefore(div, n);
  129. n.remove();
  130.  
  131. div.addEventListener('click', clickHandler);
  132. }
  133.  
  134. injectStylesIfNeeded();
  135. return true;
  136. }
  137.  
  138. function adjustNodesIfNeeded(e) {
  139. if (resizeMode != 'Original' && !adjustNodesIfNeeded.scheduled)
  140. adjustNodesIfNeeded.scheduled = setTimeout(function() {
  141. adjustNodes(e);
  142. adjustNodesIfNeeded.scheduled = 0;
  143. }, 16);
  144. }
  145.  
  146. function adjustNodes(e, clickedContainer) {
  147. var force = !!clickedContainer;
  148. var nearest = force ? clickedContainer : null;
  149.  
  150. var vids = $$('div.instant-youtube-container');
  151.  
  152. if (!nearest && e.type != 'DOMContentLoaded') {
  153. var minDistance = window.innerHeight*3/4 |0;
  154. var nearTargetY = window.innerHeight/2;
  155. vids.forEach(function(n) {
  156. var bounds = n.getBoundingClientRect();
  157. var distance = Math.abs((bounds.bottom + bounds.top)/2 - nearTargetY);
  158. if (distance < minDistance) {
  159. minDistance = distance;
  160. nearest = n;
  161. }
  162. });
  163. }
  164.  
  165. if (nearest) {
  166. var bounds = nearest.getBoundingClientRect();
  167. var nearestCenterYpct = (bounds.top + bounds.bottom)/2 / window.innerHeight;
  168. }
  169.  
  170. var resized = false;
  171.  
  172. vids.forEach(function(n) {
  173. var size = calcThumbSize(n);
  174. var w = size.w, h = size.h;
  175.  
  176. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  177. return;
  178.  
  179. if (n.style.maxWidth != w + 'px') n.style.maxWidth = w + 'px';
  180. if (n.style.height != h + 'px') n.style.height = h + 'px';
  181.  
  182. var video = $(n, 'video');
  183. if (video) {
  184. video.width = w;
  185. video.height = h;
  186. }
  187.  
  188. fixThumbnailAR(n);
  189. resized = true;
  190. });
  191.  
  192. if (resized && nearest)
  193. setTimeout(function() {
  194. var bounds = nearest.getBoundingClientRect();
  195. var h = bounds.bottom - bounds.top;
  196. var projectedCenterY = nearestCenterYpct * window.innerHeight;
  197. var projectedTop = projectedCenterY - h/2;
  198. var safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  199. window.scrollBy(0, bounds.top - safeTop);
  200. }, 16);
  201. }
  202.  
  203. function calcThumbSize(node) {
  204. var w, h;
  205. switch (resizeMode) {
  206. case 'Original':
  207. w = node.FYTE.originalWidth;
  208. h = node.FYTE.originalHeight;
  209. break;
  210. case 'Custom':
  211. w = resizeWidth;
  212. h = resizeHeight;
  213. break;
  214. case '1080p':
  215. case '720p':
  216. case '480p':
  217. case '360p':
  218. h = parseInt(resizeMode);
  219. w = Math.round(h / 9 * 16 + 0.49);
  220. break;
  221. default: // fit-to-width mode
  222. do {
  223. node = node.parentElement;
  224. // find parent node with nonzero width (i.e. independent of our video element)
  225. } while (node && !(w = node.clientWidth));
  226. if (w)
  227. h = Math.round(w / 16 * 9 + 0.49);
  228. else {
  229. w = node.clientWidth;
  230. h = node.clientHeight;
  231. }
  232. }
  233. return {w:w, h:h};
  234. }
  235.  
  236. function parseWatchPage(response) {
  237. var div = response.context;
  238. var txt = response.responseText;
  239.  
  240. // parse width & height to adjust the thumbnail
  241. var w = txt.match(/<meta property="og:video:width" content="(\d+)">/);
  242. var h = txt.match(/<meta property="og:video:height" content="(\d+)">/);
  243. if (w && h)
  244. fixThumbnailAR(div, w[1]|0, h[1]|0);
  245.  
  246. // parse video sources
  247. var m = txt.match(/ytplayer\.config\s*=\s*(\{.+?\});\s*ytplayer\.load/);
  248. var videoInfo = [];
  249. if (m) {
  250. var cfg = JSON.parse(m[1]), streams = {};
  251. cfg.args.url_encoded_fmt_stream_map.split(',').forEach(function(stream) {
  252. var params = {};
  253. stream.split('&').forEach(function(kv) {
  254. params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
  255. });
  256. streams[params.itag] = params;
  257. });
  258. cfg.args.fmt_list.split(',').forEach(function(fmt) {
  259. var itag = fmt.split('/')[0];
  260. var dimensions = fmt.split('/')[1];
  261. var stream = streams[itag];
  262. if (stream) {
  263. videoInfo.push({
  264. src: stream.url,
  265. title: stream.quality + ', ' + dimensions + ', ' + stream.type
  266. });
  267. }
  268. });
  269. } else {
  270. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  271. var text = txt.split('url_encoded_fmt_stream_map')[1];
  272. while (m = rx.exec(text)) {
  273. videoInfo.push({
  274. src: decodeURIComponent(decodeURIComponent(m[1]))
  275. });
  276. }
  277. }
  278.  
  279. var title = txt.match(/<title>(.+?)(?:\s*-\s*YouTube)?<\/title>/);
  280. if (title) {
  281. var duration = txt.match(/<meta itemprop="duration" content="\D*(\d+.*?)S?">/);
  282. var a = div.firstElementChild.appendChild(document.createElement('a'));
  283. a.className = 'instant-youtube-persistent-title';
  284. a.innerHTML = '<strong>' + title[1] + '</strong>' +
  285. (duration ? '<span>' + duration[1].replace(/[HM]/, ':0').replace(/\b0(\d\d)/, '$1') + '</span>' : '');
  286. a.href = 'https://www.youtube.com/watch?v=' + div.FYTE.videoID;
  287. a.target = '_blank';
  288. ['animation', 'webkitAnimation', 'mozAnimation'].some(function(prop) {
  289. if (prop in a.style) {
  290. a.style[prop] = 'instant-youtube-fadein 1s ease-in';
  291. setTimeout(function() { a.style[prop] = '' }, 1000);
  292. return true;
  293. }
  294. });
  295. }
  296.  
  297. if (videoInfo.length)
  298. div.FYTE.videoInfo = videoInfo;
  299.  
  300. injectStylesIfNeeded();
  301.  
  302. if (div.FYTE.state == 'scheduled play')
  303. setTimeout(function() { playDirectly(div) }, 0);
  304.  
  305. div.FYTE.state = '';
  306. }
  307.  
  308. function fixThumbnailAR(div, w, h) {
  309. var img = $(div, 'img');
  310. var thw = img.naturalWidth, thh = img.naturalHeight;
  311. if (!thw || !thh) {
  312. // thumbnail is still loading
  313. img.videoWidth = w;
  314. img.videoHeight = h;
  315. return;
  316. } else if (!w || !h) {
  317. w = img.videoWidth;
  318. h = img.videoHeight;
  319. }
  320. var divw = div.clientWidth, divh = div.clientHeight;
  321. // if both video and thumbnail are 4:3, fit the image to height
  322. if (Math.abs(h/w*divw / divh - 1) > 0.05 && Math.abs(thh/thw*divw / divh - 1) > 0.05) {
  323. img.style.cssText = img.style.cssText.replace(/\bheight:.*?;/, 'height:' + img.clientHeight + 'px!important;');
  324. if (!img.videoWidth) // skip animation if thumbnail is already loaded
  325. img.style.transition = 'height 1s ease, margin-top 1s ease';
  326. setTimeout(function() {
  327. img.style.cssText += important(h/w >= divh/divw ? 'width:auto; height:100%;' : 'width:100%; height:auto;');
  328. setTimeout(function() {
  329. img.style.transition = '';
  330. }, 1000);
  331. }, 0);
  332. }
  333. }
  334.  
  335. function clickHandler(e) {
  336. if (e.target.href)
  337. return;
  338. if (e.target.matches('.instant-youtube-options-button'))
  339. return showOptions(e);
  340. if (e.target.matches('.instant-youtube-options, .instant-youtube-options *'))
  341. return;
  342. div = e.target.closest('.instant-youtube-container');
  343. div.removeEventListener('click', clickHandler);
  344. $(div, 'svg').outerHTML = '<span class="instant-youtube-loading-button"></span>';
  345.  
  346. var alternateMode = e.shiftKey || e.target.className == 'instant-youtube-link';
  347. if ((!!playHTML5 + !!alternateMode == 1) && (div.FYTE.videoInfo || div.FYTE.state == 'querying')) {
  348. if (div.FYTE.videoInfo)
  349. playDirectly(div);
  350. else {
  351. // playback will start in parseWatchPage
  352. div.FYTE.state = 'scheduled play';
  353. // fallback to iframe in 5s
  354. setTimeout(function() {
  355. if (div.FYTE.state) {
  356. div.FYTE.state = '';
  357. switchToIFrame.call(div);
  358. }
  359. }, 5000);
  360. }
  361. }
  362. else
  363. switchToIFrame.call(div);
  364. }
  365.  
  366. function playDirectly(div) {
  367. $(div, '.instant-youtube-options-button').style.display = 'none';
  368. $(div, '.instant-youtube-link').style.display = 'none';
  369.  
  370. var video = document.createElement('video');
  371. video.controls = true;
  372. video.autoplay = true;
  373. video.style.cssText = important(
  374. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:0; transition:opacity 2s;' +
  375. 'width:'+div.clientWidth+'px; height:'+div.clientHeight+'px;');
  376. video.className = 'instant-youtube-embed';
  377. video.volume = GM_getValue('volume', 0.5);
  378.  
  379. div.FYTE.videoInfo.forEach(function(src) {
  380. var srcdom = video.appendChild(document.createElement('source'));
  381. Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
  382. srcdom.onerror = switchToIFrame.bind(div);
  383. });
  384.  
  385.  
  386. if (window.chrome) {
  387. video.addEventListener('click', function(e) {
  388. this.paused ? this.play() : this.pause();
  389. });
  390. }
  391. video.interval = (function() {
  392. return setInterval(function() {
  393. if (video.volume != GM_getValue('volume', 0.5))
  394. GM_setValue('volume', video.volume);
  395. }, 1000);
  396. })();
  397. var title = $(div, '.instant-youtube-persistent-title');
  398. if (title) {
  399. video.onpause = function() { title.removeAttribute('hidden') };
  400. video.onplay = function() { title.setAttribute('hidden', true) };
  401. }
  402. video.onloadeddata = function(e) {
  403. pauseOtherVideos(this);
  404. div.style.cssText += 'contain:none!important'; // allow fullscreen
  405. div.firstElementChild.appendChild(this);
  406. this.style.opacity = 1;
  407. var img = $(div, 'img');
  408. img.style.transition = 'opacity 1s';
  409. img.style.opacity = 0;
  410. };
  411. }
  412.  
  413. function switchToIFrame(e) {
  414. var div = this;
  415. var wrapper = div.firstElementChild;
  416. if (e) {
  417. console.log('Direct linking failed on %s, switching to IFRAME player', div.FYTE.srcEmbed);
  418. var video = e.target ? e.target.closest('video') : e.path && e.path[e.path.length-1];
  419. while (video.lastElementChild)
  420. video.lastElementChild.remove();
  421. }
  422.  
  423. wrapper.insertAdjacentHTML('beforeend',
  424. '<iframe class="instant-youtube-embed" allowtransparency="true" src="' +
  425. div.FYTE.srcEmbed.replace('http:', 'https:').replace('/v/', '/embed/') +
  426. (div.FYTE.srcEmbed.indexOf('?') > 0 ? '&' : '?') +
  427. 'html5=1' +
  428. '&autoplay=1' +
  429. '&autohide=2' +
  430. '&border=0' +
  431. '&controls=1' +
  432. '&fs=1' +
  433. '&showinfo=1' +
  434. '&ssl=1' +
  435. '&theme=dark' +
  436. '&enablejsapi=1' +
  437. '" frameborder="0" allowfullscreen width="' + div.clientWidth + '" height="' + div.clientHeight + '"></iframe>');
  438.  
  439. wrapper.lastElementChild.onload = function() {
  440. pauseOtherVideos(this);
  441. this.style.cssText = important(
  442. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:1; transition:opacity 2s;');
  443.  
  444. var div = this.closest('.instant-youtube-container');
  445. div.setAttribute('iframe', '');
  446. div.style.cssText += 'contain:none!important'; // allow fullscreen
  447. setTimeout(function() {
  448. $(div, 'img').style.display = 'none';
  449. var title = $(div, '.instant-youtube-persistent-title');
  450. if (title)
  451. title.remove();
  452. }, 2000);
  453. };
  454. }
  455.  
  456. function pauseOtherVideos(activePlayer) {
  457. [].forEach.call(activePlayer.ownerDocument.getElementsByClassName('instant-youtube-embed'), function(v) {
  458. if (v == activePlayer)
  459. return;
  460. switch (v.localName) {
  461. case 'video':
  462. if (!v.paused)
  463. v.pause();
  464. break;
  465. case 'iframe':
  466. try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {}
  467. break;
  468. }
  469. });
  470. }
  471.  
  472. function showOptions(e) {
  473. var optionsButton = e.target;
  474. optionsButton.insertAdjacentHTML('afterend', '\
  475. <div class="instant-youtube-options">\
  476. <label>Size:<br>\
  477. <select data-action="size-mode">\
  478. <option>Original</option>\
  479. <option>Fit to width</option>\
  480. <option>360p</option>\
  481. <option>480p</option>\
  482. <option>720p</option>\
  483. <option>1080p</option>\
  484. <option value="Custom">Custom...</option>\
  485. </select>\
  486. </label>\
  487. <label data-action="size-custom" ' + (resizeMode != 'Custom' ? 'disabled' : '') + '>\
  488. <input type="number" min="320" max="9999" placeholder="width" step="10" value="' + (resizeWidth||'') + '">\
  489. x\
  490. <input type="number" min="240" max="9999" placeholder="height" step="10" value="' + (resizeHeight||'') + '">\
  491. </label>\
  492. <label title="Tip: shift-clicking thumbnails will use alternative player">\
  493. <input data-action="direct" type="checkbox" ' + (playHTML5 ? 'checked' : '') + '>\
  494. Play directly\
  495. </label>\
  496. <label title="Do not process customized videos with enablejsapi=1 parameter (requires page reload)">\
  497. <input data-action="safe" type="checkbox" ' + (skipCustom ? 'checked' : '') + '>\
  498. Safe\
  499. </label>\
  500. <span data-action="buttons">\
  501. <button>OK</button>\
  502. <button>Cancel</button>\
  503. </span>\
  504. </div>\
  505. ');
  506. var options = optionsButton.nextElementSibling;
  507.  
  508. options.addEventListener('keydown', function(e) {
  509. if (e.target.localName == 'input' &&
  510. !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && e.key.match(/[.,]/))
  511. return false;
  512. });
  513.  
  514. $(options, '[data-action="size-mode"]').value = resizeMode;
  515. $(options, '[data-action="size-mode"]').addEventListener('change', function() {
  516. var v = this.value != 'Custom';
  517. var e = $(options, '[data-action="size-custom"]');
  518. e.children[0].disabled = e.children[1].disabled = v;
  519. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  520. });
  521.  
  522. $(options, '[data-action="buttons"]').addEventListener('click', function(e) {
  523. if (e.target.textContent != 'OK') {
  524. options.remove();
  525. return;
  526. }
  527. var v, shouldAdjust;
  528. if (resizeMode != (v = $(options, '[data-action="size-mode"]').value)) {
  529. GM_setValue('resize', resizeMode = v);
  530. shouldAdjust = true;
  531. }
  532. if (resizeMode == 'Custom') {
  533. var w = $(options, '[placeholder="width"]').value |0;
  534. var h = $(options, '[placeholder="height"]').value |0;
  535. if (resizeWidth != w || resizeHeight != h) {
  536. updateCustomSize(w, h);
  537. GM_setValue('width', resizeWidth);
  538. GM_setValue('height', resizeHeight);
  539. shouldAdjust = true;
  540. }
  541. }
  542. if (playHTML5 != (v = $(options, '[data-action="direct"]').checked)) {
  543. GM_setValue('playHTML5', playHTML5 = v);
  544. $$('.instant-youtube-container .instant-youtube-link').forEach(function(e) {
  545. e.textContent = playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)';
  546. });
  547. }
  548. if (skipCustom != (v = $(options, '[data-action="safe"]').checked)) {
  549. GM_setValue('skipCustom', skipCustom = v);
  550. initEmbedSelector();
  551. }
  552.  
  553. options.remove();
  554.  
  555. if (shouldAdjust)
  556. adjustNodes(e, e.target.closest('.instant-youtube-container'));
  557. });
  558. }
  559.  
  560. function updateCustomSize(w, h) {
  561. resizeWidth = Math.min(9999, Math.max(320, w|0 || resizeWidth|0));
  562. resizeHeight = Math.min(9999, Math.max(240, h|0 || resizeHeight|0));
  563. }
  564.  
  565. function important(cssText) {
  566. return cssText.replace(/;/g, '!important;');
  567. }
  568.  
  569. function injectStylesIfNeeded() {
  570. if (document.head.innerHTML.indexOf('.instant-youtube-container') > 0)
  571. return;
  572. GM_addStyle(important('\
  573. .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;}\
  574. .instant-youtube-container .instant-youtube-wrapper {width:100%; height:100%;}\
  575. .instant-youtube-container .instant-youtube-play-button {position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; width:85px; height:60px;}\
  576. .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==");}\
  577. .instant-youtube-container:hover .ytp-large-play-button-svg {fill:#CC181E;}\
  578. .instant-youtube-container .instant-youtube-link {\
  579. position:absolute; top:50%; left:0; right:0; width:20em; height:20px; margin:60px auto; padding:0; border:none; \
  580. display:block; text-align:center; text-decoration:none; color:white; text-shadow:1px 1px 3px black; font-weight:bold;\
  581. }\
  582. .instant-youtube-container span.instant-youtube-link {font-weight:normal; font-size:12px;}\
  583. .instant-youtube-container .instant-youtube-link:hover {color:white; text-decoration:underline; background:transparent;}\
  584. .instant-youtube-container iframe {z-index:10;}\
  585. .instant-youtube-container .instant-youtube-persistent-title {\
  586. display:block; z-index:9; background-color:rgba(0,0,0,0.5); color:white;\
  587. width:100%; top:0; left:0; right:0; position:absolute; z-index: 9;\
  588. color:white; text-shadow:1px 1px 2px black; text-align:center; text-decoration:none;\
  589. margin:0; padding:7px; border:none;\
  590. }\
  591. .instant-youtube-container .instant-youtube-persistent-title strong:after {content:" - watch on Youtube"; font-weight:normal; margin-right:1ex;}\
  592. .instant-youtube-container .instant-youtube-persistent-title span {color:inherit;}\
  593. .instant-youtube-container .instant-youtube-persistent-title span:before {content:"(";}\
  594. .instant-youtube-container .instant-youtube-persistent-title span:after {content:")";}\
  595. \
  596. @-webkit-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  597. @-moz-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  598. @keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  599. \
  600. .instant-youtube-container:not(:hover) .instant-youtube-persistent-title[hidden] {display:none; margin:0;}\
  601. .instant-youtube-container .instant-youtube-persistent-title:hover {text-decoration:underline;}\
  602. .instant-youtube-container .instant-youtube-persistent-title strong {color:white;}\
  603. \
  604. .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;}\
  605. .instant-youtube-container .instant-youtube-options-button:hover {opacity:1; background:rgba(0,0,0,0.5);}\
  606. \
  607. .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;}\
  608. .instant-youtube-container .instant-youtube-options * {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;}\
  609. .instant-youtube-container .instant-youtube-options > label {margin-top:1ex;}\
  610. .instant-youtube-container .instant-youtube-options > label > * {display:inline;}\
  611. .instant-youtube-container .instant-youtube-options select {-webkit-appearance:menulist;}\
  612. .instant-youtube-container .instant-youtube-options [data-action="size-custom"] input {width:9ex; border:1px solid #666; padding:.5ex .5ex .4ex;}\
  613. .instant-youtube-container .instant-youtube-options [data-action="buttons"] {margin-top:1em;}\
  614. .instant-youtube-container .instant-youtube-options button {padding:.5ex 2ex; margin:0 1ex 0 0; border:2px solid gray; font-weight:bold;}\
  615. .instant-youtube-container .instant-youtube-options button:hover {border-color:white;}\
  616. .instant-youtube-container .instant-youtube-options > [disabled] {opacity:0.25;}\
  617. '));
  618. }