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-24 提交的版本,查看 最新版本

  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. // @description:ru На порядок ускоряет время загрузки страниц с большим количеством вставленных Youtube-видео. С первого момента загрузки страницы появляются не тормозящие заглушки, которые можно щелкнуть для загрузки плеера. Долю секунды спустя появляются кавер-картинки и название видео. В опциях можно включить режим использования упрощенного браузерного плеера (макс. 720p).
  5. // @version 2.3.4
  6. // @include *
  7. // @exclude https://www.youtube.com/*
  8. // @author wOxxOm
  9. // @namespace wOxxOm.scripts
  10. // @license MIT License
  11. // @grant GM_getValue
  12. // @grant GM_setValue
  13. // @grant GM_addStyle
  14. // @grant GM_xmlhttpRequest
  15. // @connect www.youtube.com
  16. // @connect youtube.com
  17. // @run-at document-start
  18. // @require https://greasyfork.org/scripts/12228/code/setMutationHandler.js
  19. // @icon https://i.imgur.com/4YpDBwa.png
  20. // @compatible chrome
  21. // @compatible firefox
  22. // @compatible opera
  23. // ==/UserScript==
  24.  
  25. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  26.  
  27. var resizeMode = GM_getValue('resize', 'Fit to width');
  28. if (typeof resizeMode != 'string')
  29. resizeMode = resizeMode ? 'Fit to width' : 'Original';
  30.  
  31. var resizeWidth = GM_getValue('width', 1280) |0;
  32. var resizeHeight = GM_getValue('height', 720) |0;
  33. updateCustomSize();
  34.  
  35. var playHTML5 = !!GM_getValue('playHTML5', false);
  36. var skipCustom = !!GM_getValue('skipCustom', true);
  37. var showStoryboard = !!GM_getValue('showStoryboard', true);
  38.  
  39. var embedSelector = 'iframe[src*="youtube.com/embed"], embed[src*="youtube.com/v"], iframe[src*="youtube.com%2Fembed"]' +
  40. (location.hostname.match(/\bgoogle\.\w{2,3}(\.\w{2,3})?$/) ? ', .g-blk a[href*="youtube.com/watch"][data-ved]' : '');
  41.  
  42. var _ = initTL();
  43.  
  44. document.addEventListener('DOMContentLoaded', function(e) {
  45. adjustNodesIfNeeded(e);
  46. injectStylesIfNeeded();
  47. });
  48.  
  49. window.addEventListener('resize', adjustNodesIfNeeded, true);
  50. window.addEventListener('message', function(e) {
  51. if (e.data == 'iframe-allowfs') {
  52. $$('iframe:not([allowfullscreen])').some(function(iframe) {
  53. if (iframe.contentWindow == e.source) {
  54. iframe.allowFullscreen = true;
  55. return true;
  56. }
  57. });
  58. if (window != window.top)
  59. window.parent.postMessage('iframe-allowfs', '*');
  60. }
  61. });
  62.  
  63. processEmbeds($$(embedSelector));
  64. setMutationHandler(document, embedSelector, processEmbeds);
  65.  
  66. function processEmbeds(nodes) {
  67. function decodeEmbedUrl(url) {
  68. return url.indexOf('youtube.com%2Fembed') > 0
  69. ? decodeURIComponent(url.replace(/^.*?(http[^&?=]+?youtube.com%2Fembed[^&]+).*$/i, '$1'))
  70. : url;
  71. }
  72. for (var i=0, nl=nodes.length, n; i<nl && (n=nodes[i]); i++) {
  73. var np = n.parentNode, npw;
  74. var src = n.src || n.href || '';
  75. var srcFixed = decodeEmbedUrl(src).replace(/\/(watch\?v=|v\/)/, '/embed/');
  76. if (src.indexOf('cdn.embedly.com/') > 0 ||
  77. resizeMode != 'Original' && np && np.children.length == 1 && !np.className && !np.id)
  78. {
  79. n = location.hostname == 'disqus.com' ? np.parentNode : np;
  80. np = n.parentNode;
  81. }
  82. if (!np ||
  83. skipCustom && srcFixed.indexOf('enablejsapi=1') > 0 ||
  84. np.localName == 'object' && !np.parentNode ||
  85. n.className.indexOf('instant-youtube-') >= 0 ||
  86. srcFixed.indexOf('autoplay=1') > 0 ||
  87. n.onload // skip some retarded loaders
  88. )
  89. continue;
  90.  
  91. var id = srcFixed.match(/(?:embed\/|v[=\/])([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
  92. if (!id)
  93. continue;
  94. id = id[1];
  95.  
  96. if (n.localName == 'a')
  97. n = np;
  98.  
  99. var div = document.createElement('div');
  100. div.className = 'instant-youtube-container';
  101. div.FYTE = {
  102. state: 'querying',
  103. srcEmbed: srcFixed.replace(/&$/, ''),
  104. videoID: id,
  105. originalWidth: nodes[i].width|0 || n.clientWidth|0,
  106. originalHeight: nodes[i].height|0 || n.clientHeight|0,
  107. };
  108. div.FYTE.srcEmbedFixed = div.FYTE.srcEmbed.replace(/^http:/, 'https:').replace(/&?wmode=\w+/, '').replace(/[?&]feature=oembed/, '');
  109. div.FYTE.srcWatchFixed = div.FYTE.srcEmbedFixed.replace(/\/embed\//, '/watch?v=');
  110.  
  111. var divSize = calcContainerSize(div, n);
  112. var origStyle = getComputedStyle(n);
  113. div.style.cssText = important(
  114. (origStyle.hasOwnProperty('position') ? Object.keys(origStyle) : Object.values(origStyle))
  115. .filter(function(k) { return !!k.match(/^(position|left|right|top|bottom|margin.*?)$/) })
  116. .map(function(k) { return k + ':' + origStyle[k] })
  117. .join(';').replace(/\b[^;:]+:(auto|static)(!\s*important)?;/g, '') +
  118. ';max-width:' + divSize.w + 'px; height:' + divSize.h + 'px;');
  119.  
  120. // prevent parent clipping
  121. for (var node=np, style; node && (style=getComputedStyle(node)); node=node.parentElement)
  122. if ((style.overflow+style.overflowX+style.overflowY).match(/hidden|scroll/))
  123. node.style.cssText = node.style.cssText.replace(/\boverflow(-[xy])?:[^;]+/g, '') +
  124. important('overflow:visible;overflow-x:visible;overflow-y:visible;');
  125.  
  126. var wrapper = div.appendChild(document.createElement('div'));
  127. wrapper.className = 'instant-youtube-wrapper';
  128.  
  129. var img = wrapper.appendChild(document.createElement('img'));
  130. img.className = 'instant-youtube-thumbnail';
  131. img.src = 'https://i.ytimg.com/vi/' + id + '/maxresdefault.jpg';
  132. 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; max-width:none; max-height:none;');
  133.  
  134. img.title = _('Shift-click to use alternative player');
  135. img.onload = function(e) {
  136. var img = e.target;
  137. if (img.naturalWidth <= 120)
  138. return img.onerror(e);
  139. var fitToWidth = true;
  140. if (img.naturalHeight) {
  141. var ratio = img.naturalWidth / img.naturalHeight;
  142. if (ratio > 4.1/3 && ratio < divSize.w/divSize.h) {
  143. img.style.cssText += important('width:auto; height:100%;');
  144. fitToWidth = false;
  145. }
  146. }
  147. if (fitToWidth) {
  148. img.style.cssText += important('width:100%; height:auto;');
  149. }
  150. if (img.videoWidth)
  151. fixThumbnailAR(div);
  152. img.style.opacity = 1;
  153. };
  154. img.onerror = function(e) {
  155. var img = e.target;
  156. if (img.src.indexOf('maxresdefault') > 0)
  157. img.src = img.src.replace('maxresdefault','hqdefault');
  158. };
  159.  
  160. GM_xmlhttpRequest({
  161. method: 'GET',
  162. url: 'https://www.youtube.com/get_video_info?video_id=' + div.FYTE.videoID + '&el=detailpage',
  163. headers: {'Accept-Encoding': 'gzip'},
  164. context: div,
  165. onload: parseVideoInfo
  166. });
  167.  
  168. translateHTML(wrapper, 'beforeend', '\
  169. <a class="instant-youtube-title" target="_blank" href="' + div.FYTE.srcWatchFixed + '">&nbsp;</a>\
  170. <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>\
  171. <span tl class="instant-youtube-link">' + (playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  172. <div class="instant-youtube-storyboard"></div>\
  173. <div tl class="instant-youtube-options-button">Options</div>\
  174. ');
  175.  
  176. if (np.localName == 'object')
  177. n = np;
  178. n.parentNode.insertBefore(div, n);
  179. n.remove();
  180.  
  181. div.addEventListener('click', clickHandler);
  182. if (showStoryboard)
  183. updateHoverHandler(div);
  184. }
  185.  
  186. injectStylesIfNeeded();
  187. return true;
  188. }
  189.  
  190. function updateHoverHandler(div) {
  191. if (!showStoryboard) {
  192. var storyboard = $(div, '.instant-youtube-storyboard');
  193. if (storyboard.innerHTML)
  194. storyboard.innerHTML = '';
  195. return;
  196. }
  197. div.addEventListener('mouseover', storyboardHoverHandler);
  198.  
  199. function storyboardHoverHandler(e) {
  200. if (!showStoryboard)
  201. return;
  202. div.removeEventListener('mouseover', storyboardHoverHandler);
  203. $(div, '.instant-youtube-storyboard').innerHTML = '123'
  204. .replace(/./g, '<div><img src="https://i.ytimg.com/vi/' + div.FYTE.videoID + '/$&.jpg"></div>');
  205. }
  206. }
  207.  
  208. function adjustNodesIfNeeded(e) {
  209. if (resizeMode != 'Original' && !adjustNodesIfNeeded.scheduled)
  210. adjustNodesIfNeeded.scheduled = setTimeout(function() {
  211. adjustNodes(e);
  212. adjustNodesIfNeeded.scheduled = 0;
  213. }, 16);
  214. }
  215.  
  216. function adjustNodes(e, clickedContainer) {
  217. var force = !!clickedContainer;
  218. var nearest = force ? clickedContainer : null;
  219.  
  220. var vids = $$('div.instant-youtube-container');
  221.  
  222. if (!nearest && e.type != 'DOMContentLoaded') {
  223. var minDistance = window.innerHeight*3/4 |0;
  224. var nearTargetY = window.innerHeight/2;
  225. vids.forEach(function(n) {
  226. var bounds = n.getBoundingClientRect();
  227. var distance = Math.abs((bounds.bottom + bounds.top)/2 - nearTargetY);
  228. if (distance < minDistance) {
  229. minDistance = distance;
  230. nearest = n;
  231. }
  232. });
  233. }
  234.  
  235. if (nearest) {
  236. var bounds = nearest.getBoundingClientRect();
  237. var nearestCenterYpct = (bounds.top + bounds.bottom)/2 / window.innerHeight;
  238. }
  239.  
  240. var resized = false;
  241.  
  242. vids.forEach(function(n) {
  243. var size = calcContainerSize(n);
  244. var w = size.w, h = size.h;
  245.  
  246. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  247. return;
  248.  
  249. if (n.style.maxWidth != w + 'px') n.style.maxWidth = w + 'px';
  250. if (n.style.height != h + 'px') n.style.height = h + 'px';
  251.  
  252. var video = $(n, 'video');
  253. if (video) {
  254. video.width = w;
  255. video.height = h;
  256. }
  257.  
  258. fixThumbnailAR(n);
  259. resized = true;
  260. });
  261.  
  262. if (resized && nearest)
  263. setTimeout(function() {
  264. var bounds = nearest.getBoundingClientRect();
  265. var h = bounds.bottom - bounds.top;
  266. var projectedCenterY = nearestCenterYpct * window.innerHeight;
  267. var projectedTop = projectedCenterY - h/2;
  268. var safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  269. window.scrollBy(0, bounds.top - safeTop);
  270. }, 16);
  271. }
  272.  
  273. function calcContainerSize(div, origNode) {
  274. var w, h;
  275. origNode = origNode || div;
  276. switch (resizeMode) {
  277. case 'Original':
  278. w = div.FYTE.originalWidth;
  279. h = div.FYTE.originalHeight;
  280. break;
  281. case 'Custom':
  282. w = resizeWidth;
  283. h = resizeHeight;
  284. break;
  285. case '1080p':
  286. case '720p':
  287. case '480p':
  288. case '360p':
  289. h = parseInt(resizeMode);
  290. w = h / 9 * 16;
  291. break;
  292. default: // fit-to-width mode
  293. var n = origNode;
  294. do {
  295. n = n.parentElement;
  296. // find parent node with nonzero width (i.e. independent of our video element)
  297. } while (n && !(w = n.clientWidth));
  298. if (w)
  299. h = w / 16 * 9;
  300. else {
  301. w = origNode.clientWidth;
  302. h = origNode.clientHeight;
  303. }
  304. }
  305. var style = getComputedStyle(origNode.parentElement);
  306. var parentWidth = parseFloat(style.width) - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
  307. if (parentWidth > 0 && parentWidth < w) {
  308. h = parentWidth / w * h;
  309. w = parentWidth;
  310. }
  311. if (resizeMode == 'Fit to width' && h < div.FYTE.originalHeight)
  312. h = w / div.FYTE.originalWidth * div.FYTE.originalHeight;
  313.  
  314. return {w:w, h:h};
  315. }
  316.  
  317. function parseVideoInfo(response) {
  318. var div = response.context;
  319. var txt = response.responseText;
  320. var info = tryCatch(function() { return JSON.parse(txt.replace(/(\w+)=?(.*?)(&|$)/g, '"$1":"$2",').replace(/^(.+?),?$/, '{$1}')) });
  321. var videoSources = [];
  322.  
  323. // parse width & height to adjust the thumbnail
  324. var m = decodeURIComponent(txt).match(/\b(\d+)x(\d+)\b/);
  325. if (m)
  326. fixThumbnailAR(div, m[1]|0, m[2]|0);
  327.  
  328. // parse video sources
  329. if (info.url_encoded_fmt_stream_map && info.fmt_list) {
  330. var streams = {};
  331. decodeURIComponent(info.url_encoded_fmt_stream_map).split(',').forEach(function(stream) {
  332. var params = {};
  333. stream.split('&').forEach(function(kv) {
  334. params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
  335. });
  336. streams[params.itag] = params;
  337. });
  338. decodeURIComponent(info.fmt_list).split(',').forEach(function(fmt) {
  339. var itag = fmt.split('/')[0];
  340. var dimensions = fmt.split('/')[1];
  341. var stream = streams[itag];
  342. if (stream) {
  343. videoSources.push({
  344. src: stream.url,
  345. title: stream.quality + ', ' + dimensions + ', ' + stream.type
  346. });
  347. }
  348. });
  349. } else {
  350. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  351. var text = decodeURIComponent(txt).split('url_encoded_fmt_stream_map')[1];
  352. while (m = rx.exec(text)) {
  353. videoSources.push({
  354. src: decodeURIComponent(decodeURIComponent(m[1]))
  355. });
  356. }
  357. }
  358.  
  359. var duration = info.length_seconds|0 || '';
  360. if (duration) {
  361. var d = new Date(null);
  362. d.setSeconds(duration);
  363. duration = d.toISOString().replace(/^.+?T[0:]{0,4}(.+?)\..+$/, '<span>$1</span>');
  364. }
  365. var title = decodeURIComponent(info.title || info.reason || '').replace(/\+/g, ' ');
  366. if (title || duration) {
  367. $(div, '.instant-youtube-title').innerHTML = (title ? '<strong>' + title + '</strong>' : '') + duration;
  368. }
  369. if (info.reason)
  370. div.setAttribute('disabled', '');
  371.  
  372. if (videoSources.length)
  373. div.FYTE.videoSources = videoSources;
  374.  
  375. injectStylesIfNeeded();
  376.  
  377. if (div.FYTE.state == 'scheduled play')
  378. setTimeout(function() { playDirectly(div) }, 0);
  379.  
  380. div.FYTE.state = '';
  381. }
  382.  
  383. function fixThumbnailAR(div, w, h) {
  384. var img = $(div, 'img');
  385. var thw = img.naturalWidth, thh = img.naturalHeight;
  386. if (w && h) { // means thumbnail is still loading
  387. img.videoWidth = w;
  388. img.videoHeight = h;
  389. return;
  390. }
  391. w = img.videoWidth;
  392. h = img.videoHeight;
  393. var divw = div.clientWidth, divh = div.clientHeight;
  394. // if both video and thumbnail are 4:3, fit the image to height
  395. //console.log(divw, divh, thw, thh, w, h, h/w*divw / divh - 1, thh/thw*divw / divh - 1);
  396. if (Math.abs(h/w*divw / divh - 1) > 0.05 && Math.abs(thh/thw*divw / divh - 1) > 0.05) {
  397. img.style.maxHeight = img.clientHeight + 'px';
  398. if (!img.videoWidth) // skip animation if thumbnail is already loaded
  399. img.style.transition = 'height 1s ease, margin-top 1s ease';
  400. setTimeout(function() {
  401. img.style.maxHeight = 'none';
  402. img.style.cssText += important(h/w >= divh/divw ? 'width:auto; height:100%;' : 'width:100%; height:auto;');
  403. setTimeout(function() {
  404. img.style.transition = '';
  405. }, 1000);
  406. }, 0);
  407. }
  408. }
  409.  
  410. function clickHandler(e) {
  411. if (e.target.href)
  412. return;
  413. if (e.target.matches('.instant-youtube-options-button')) {
  414. showOptions(e);
  415. e.preventDefault();
  416. e.stopPropagation();
  417. return;
  418. }
  419. if (e.target.matches('.instant-youtube-options, .instant-youtube-options *'))
  420. return;
  421.  
  422. e.preventDefault();
  423. e.stopPropagation();
  424.  
  425. div = e.target.closest('.instant-youtube-container');
  426. div.removeEventListener('click', clickHandler);
  427.  
  428. $$(div, '.instant-youtube-wrapper > *:not(img):not(a)').forEach(function(e) { e.style.cssText = 'display:none!important' });
  429. $(div, 'svg').outerHTML = '<span class="instant-youtube-loading-button"></span>';
  430.  
  431. if (window != window.top)
  432. window.parent.postMessage('iframe-allowfs', '*');
  433.  
  434. var alternateMode = e.shiftKey || e.target.className == 'instant-youtube-link';
  435. if ((!!playHTML5 + !!alternateMode == 1) && (div.FYTE.videoSources || div.FYTE.state == 'querying')) {
  436. if (div.FYTE.videoSources)
  437. playDirectly(div);
  438. else {
  439. // playback will start in parseVideoInfo
  440. div.FYTE.state = 'scheduled play';
  441. // fallback to iframe in 5s
  442. setTimeout(function() {
  443. if (div.FYTE.state) {
  444. div.FYTE.state = '';
  445. switchToIFrame.call(div);
  446. }
  447. }, 5000);
  448. }
  449. }
  450. else
  451. switchToIFrame.call(div);
  452. }
  453.  
  454. function playDirectly(div) {
  455. var video = document.createElement('video');
  456. video.controls = true;
  457. video.autoplay = true;
  458. video.style.cssText = important(
  459. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:0; transition:opacity 2s;' +
  460. 'width:100%; height:100%;');
  461. video.className = 'instant-youtube-embed';
  462. video.volume = GM_getValue('volume', 0.5);
  463.  
  464. div.FYTE.videoSources.forEach(function(src) {
  465. var srcdom = video.appendChild(document.createElement('source'));
  466. Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
  467. srcdom.onerror = switchToIFrame.bind(div);
  468. });
  469.  
  470.  
  471. if (window.chrome) {
  472. video.addEventListener('click', function(e) {
  473. this.paused ? this.play() : this.pause();
  474. });
  475. }
  476. video.interval = (function() {
  477. return setInterval(function() {
  478. if (video.volume != GM_getValue('volume', 0.5))
  479. GM_setValue('volume', video.volume);
  480. }, 1000);
  481. })();
  482. var title = $(div, '.instant-youtube-title');
  483. if (title) {
  484. video.onpause = function() { title.removeAttribute('hidden') };
  485. video.onplay = function() { title.setAttribute('hidden', true) };
  486. }
  487. video.onloadeddata = function(e) {
  488. pauseOtherVideos(this);
  489. div.style.cssText += 'contain:none!important'; // allow fullscreen
  490. div.firstElementChild.appendChild(this);
  491. this.style.opacity = 1;
  492. var img = $(div, 'img');
  493. img.style.transition = 'opacity 1s';
  494. img.style.opacity = 0;
  495. };
  496. }
  497.  
  498. function switchToIFrame(e) {
  499. var div = this;
  500. var wrapper = div.firstElementChild;
  501. if (e) {
  502. console.log('[FYTE] Direct linking canceled on %s, switching to IFRAME player', div.FYTE.srcEmbed);
  503. var video = e.target ? e.target.closest('video') : e.path && e.path[e.path.length-1];
  504. while (video.lastElementChild)
  505. video.lastElementChild.remove();
  506. }
  507.  
  508. wrapper.insertAdjacentHTML('beforeend',
  509. '<iframe class="instant-youtube-embed" allowtransparency="true" src="' + div.FYTE.srcEmbedFixed +
  510. (div.FYTE.srcEmbedFixed.indexOf('?') > 0 ? '&' : '?') +
  511. 'html5=1' +
  512. '&autoplay=1' +
  513. '&autohide=2' +
  514. '&border=0' +
  515. '&controls=1' +
  516. '&fs=1' +
  517. '&showinfo=1' +
  518. '&ssl=1' +
  519. '&theme=dark' +
  520. '&enablejsapi=1' +
  521. '" frameborder="0" allowfullscreen width="100%" height="100%"></iframe>');
  522.  
  523. wrapper.lastElementChild.onload = function() {
  524. pauseOtherVideos(this);
  525. this.style.cssText = important(
  526. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:1; transition:opacity 2s;');
  527.  
  528. div.setAttribute('iframe', '');
  529. div.style.cssText += 'contain:none!important'; // allow fullscreen
  530. setTimeout(function() {
  531. $(div, 'img').style.display = 'none';
  532. var title = $(div, '.instant-youtube-title');
  533. if (title)
  534. title.remove();
  535. }, 2000);
  536. };
  537. }
  538.  
  539. function pauseOtherVideos(activePlayer) {
  540. $$(activePlayer.ownerDocument, '.instant-youtube-embed').forEach(function(v) {
  541. if (v == activePlayer)
  542. return;
  543. switch (v.localName) {
  544. case 'video':
  545. if (!v.paused)
  546. v.pause();
  547. break;
  548. case 'iframe':
  549. try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {}
  550. break;
  551. }
  552. });
  553. }
  554.  
  555. function showOptions(e) {
  556. var optionsButton = e.target;
  557. translateHTML(optionsButton, 'afterend', '\
  558. <div class="instant-youtube-options">\
  559. <label tl>Size:<br>\
  560. <select data-action="size-mode">\
  561. <option tl value="Original">Original\
  562. <option tl value="Fit to width">Fit to width\
  563. <option>360p\
  564. <option>480p\
  565. <option>720p\
  566. <option>1080p\
  567. <option tl value="Custom">Custom...\
  568. </select>\
  569. </label>\
  570. <label data-action="size-custom" ' + (resizeMode != 'Custom' ? 'disabled' : '') + '>\
  571. <input type="number" min="320" max="9999" tl-placeholder="width" data-action="width" step="1" value="' + (resizeWidth||'') + '">\
  572. x\
  573. <input type="number" min="240" max="9999" tl-placeholder="height" data-action="height" step="1" value="' + (resizeHeight||'') + '">\
  574. </label>\
  575. <label tl="content,title" title="Show 3 thumbnails on mouse hover: at 25%, 50%, 75% of video duration">\
  576. <input data-action="storyboard" type="checkbox" ' + (showStoryboard ? 'checked' : '') + '>\
  577. Storyboard thumbs\
  578. </label>\
  579. <label tl="content,title" title="Tip: shift-clicking thumbnails will use alternative player">\
  580. <input data-action="direct" type="checkbox" ' + (playHTML5 ? 'checked' : '') + '>\
  581. Play directly\
  582. </label>\
  583. <label tl="content,title" title="Do not process customized videos with enablejsapi=1 parameter (requires page reload)">\
  584. <input data-action="safe" type="checkbox" ' + (skipCustom ? 'checked' : '') + '>\
  585. Safe\
  586. </label>\
  587. <span data-action="buttons">\
  588. <button tl data-action="ok">OK</button>\
  589. <button tl data-action="cancel">Cancel</button>\
  590. </span>\
  591. </div>\
  592. ');
  593. var options = optionsButton.nextElementSibling;
  594.  
  595. options.addEventListener('keydown', function(e) {
  596. if (e.target.localName == 'input' &&
  597. !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && e.key.match(/[.,]/))
  598. return false;
  599. });
  600.  
  601. $(options, '[data-action="size-mode"]').value = resizeMode;
  602. $(options, '[data-action="size-mode"]').addEventListener('change', function() {
  603. var v = this.value != 'Custom';
  604. var e = $(options, '[data-action="size-custom"]');
  605. e.children[0].disabled = e.children[1].disabled = v;
  606. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  607. });
  608.  
  609. $(options, '[data-action="buttons"]').addEventListener('click', function(e) {
  610. if (e.target.dataset.action != 'ok') {
  611. options.remove();
  612. return;
  613. }
  614. var v, shouldAdjust;
  615. if (resizeMode != (v = $(options, '[data-action="size-mode"]').value)) {
  616. GM_setValue('resize', resizeMode = v);
  617. shouldAdjust = true;
  618. }
  619. if (resizeMode == 'Custom') {
  620. var w = $(options, '[data-action="width"]').value |0;
  621. var h = $(options, '[data-action="height"]').value |0;
  622. if (resizeWidth != w || resizeHeight != h) {
  623. updateCustomSize(w, h);
  624. GM_setValue('width', resizeWidth);
  625. GM_setValue('height', resizeHeight);
  626. shouldAdjust = true;
  627. }
  628. }
  629. if (showStoryboard != (v = $(options, '[data-action="storyboard"]').checked)) {
  630. GM_setValue('showStoryboard', showStoryboard = v);
  631. $$('.instant-youtube-container').forEach(updateHoverHandler);
  632. }
  633. if (playHTML5 != (v = $(options, '[data-action="direct"]').checked)) {
  634. GM_setValue('playHTML5', playHTML5 = v);
  635. $$('.instant-youtube-container .instant-youtube-link').forEach(function(e) {
  636. e.textContent = playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)';
  637. });
  638. }
  639. if (skipCustom != (v = $(options, '[data-action="safe"]').checked)) {
  640. GM_setValue('skipCustom', skipCustom = v);
  641. }
  642.  
  643. options.remove();
  644.  
  645. if (shouldAdjust)
  646. adjustNodes(e, e.target.closest('.instant-youtube-container'));
  647. });
  648. }
  649.  
  650. function updateCustomSize(w, h) {
  651. resizeWidth = Math.min(9999, Math.max(320, w|0 || resizeWidth|0));
  652. resizeHeight = Math.min(9999, Math.max(240, h|0 || resizeHeight|0));
  653. }
  654.  
  655. function important(cssText) {
  656. return cssText.replace(/;/g, '!important;');
  657. }
  658.  
  659. function tryCatch(func) {
  660. try {
  661. return func();
  662. } catch(e) {
  663. console.log(e);
  664. }
  665. }
  666.  
  667. function $(selORnode, sel) {
  668. return sel ? selORnode.querySelector(sel)
  669. : document.querySelector(selORnode);
  670. }
  671.  
  672. function $$(selORnode, sel) {
  673. return Array.prototype.slice.call(
  674. sel ? selORnode.querySelectorAll(sel)
  675. : document.querySelectorAll(selORnode));
  676. }
  677.  
  678. function translateHTML(parent, place, html) {
  679. var tmp = document.createElement('div');
  680. tmp.innerHTML = html;
  681. $$(tmp, '[tl]').forEach(function(node) {
  682. (node.getAttribute('tl') || 'content').split(',').forEach(function(what) {
  683. var child, src, tl;
  684. if (what == 'content') {
  685. for (var i = node.childNodes.length-1, n; (i>=0) && (n=node.childNodes[i]); i--) {
  686. if (n.nodeType == Node.TEXT_NODE && n.textContent.trim()) {
  687. child = n;
  688. break;
  689. }
  690. }
  691. } else
  692. child = node.getAttributeNode(what);
  693. if (!child)
  694. return;
  695. src = child.textContent;
  696. srcTrimmed = src.trim();
  697. tl = src.replace(srcTrimmed, _(srcTrimmed));
  698. if (src != tl)
  699. child.textContent = tl;
  700. });
  701. });
  702. parent.insertAdjacentHTML(place, tmp.innerHTML);
  703. }
  704.  
  705. function initTL(src) {
  706. var tlSource = {
  707. 'watch on Youtube': {
  708. 'ru': 'открыть на Youtube',
  709. },
  710. 'Play with Youtube player': {
  711. 'ru': 'Включить плеер Youtube',
  712. },
  713. 'Play directly (up to 720p)': {
  714. 'ru': 'Включить напрямую (макс. 720p)',
  715. },
  716. 'Shift-click to use alternative player': {
  717. 'ru': 'Shift-клик для смены типа плеера',
  718. },
  719. 'Options': {
  720. 'ru': 'Опции',
  721. },
  722. 'Size:': {
  723. 'ru': 'Размер:',
  724. },
  725. 'Original': {
  726. 'ru': 'Исходный',
  727. },
  728. 'Fit to width': {
  729. 'ru': 'На всю ширину',
  730. },
  731. 'Custom...': {
  732. 'ru': 'Настроить...',
  733. },
  734. 'width': {
  735. 'ru': 'ширина',
  736. },
  737. 'height': {
  738. 'ru': 'высота',
  739. },
  740. 'Storyboard thumbs': {
  741. 'ru': 'Раскадровка',
  742. },
  743. 'Show 3 thumbnails on mouse hover: at 25%, 50%, 75% of video duration': {
  744. 'ru': 'Показывать 3 миникадра при наведении мыши: моменты на 25%, 50%, 75% времени видео',
  745. },
  746. 'Play directly': {
  747. 'ru': 'Плеер браузера',
  748. },
  749. 'Tip: shift-clicking thumbnails will use alternative player': {
  750. 'ru': 'Удерживайте клавишу Shift при щелчке на картинке для альтернативного плеера',
  751. },
  752. 'Safe': {
  753. 'ru': 'Консервативный режим',
  754. },
  755. 'Do not process customized videos with enablejsapi=1 parameter (requires page reload)': {
  756. 'ru': 'Не обрабатывать нестандартные видео с параметром enablejsapi=1 (подействует после обновления страницы)',
  757. },
  758. 'OK': {
  759. 'ru': 'ОК',
  760. },
  761. 'Cancel': {
  762. 'ru': 'Оменить',
  763. },
  764. };
  765. var browserLang = navigator.language || navigator.languages && navigator.languages[0] || '';
  766. var browserLangMajor = browserLang.replace(/-.+/, '');
  767. var tl = {};
  768. Object.keys(tlSource).forEach(function(k) {
  769. var langs = tlSource[k];
  770. var text = langs[browserLang] || langs[browserLangMajor];
  771. if (text)
  772. tl[k] = text;
  773. });
  774. return function(src) { return tl[src] || src };
  775. }
  776.  
  777. function injectStylesIfNeeded() {
  778. if (document.head.innerHTML.indexOf('.instant-youtube-container') > 0)
  779. return;
  780. GM_addStyle(important('\
  781. .instant-youtube-container {contain:strict; position:relative; overflow:hidden; cursor:pointer; background:black; padding:0; margin:0; font:normal 14px/1.0 sans-serif,Arial,Helvetica,Verdana; text-align:center;}\
  782. .instant-youtube-container[disabled] {background: #888;}\
  783. .instant-youtube-container[disabled] .instant-youtube-storyboard {display:none;}\
  784. .instant-youtube-container .instant-youtube-wrapper {width:100%; height:100%;}\
  785. .instant-youtube-container .instant-youtube-play-button {position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; width:85px; height:60px; display:block;}\
  786. .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==");}\
  787. .instant-youtube-container:hover .ytp-large-play-button-svg {fill:#CC181E;}\
  788. .instant-youtube-container .instant-youtube-link {\
  789. position:absolute; top:50%; left:0; right:0; width:20em; height:20px; margin:60px auto; padding:0; border:none; \
  790. display:block; text-align:center; text-decoration:none; color:white; text-shadow:1px 1px 3px black; font-weight:bold;\
  791. }\
  792. .instant-youtube-container span.instant-youtube-link {font-weight:normal; font-size:12px; z-index:8;}\
  793. .instant-youtube-container .instant-youtube-link:hover {color:white; text-decoration:underline; background:transparent;}\
  794. .instant-youtube-container iframe {z-index:10;}\
  795. .instant-youtube-container .instant-youtube-title {\
  796. display:block; z-index:9; background-color:rgba(0,0,0,0.5); color:white;\
  797. width:100%; top:0; left:0; right:0; position:absolute; z-index: 9;\
  798. color:white; text-shadow:1px 1px 2px black; text-align:center; text-decoration:none;\
  799. margin:0; padding:7px; border:none;\
  800. }\
  801. .instant-youtube-container .instant-youtube-title strong {font:bold 14px/1.0 sans-serif,Arial,Helvetica,Verdana;}\
  802. .instant-youtube-container .instant-youtube-title strong:after {content:" - ' + _('watch on Youtube') + '"; font-weight:normal; margin-right:1ex;}\
  803. .instant-youtube-container .instant-youtube-title span {color:inherit;}\
  804. .instant-youtube-container .instant-youtube-title span:before {content:"(";}\
  805. .instant-youtube-container .instant-youtube-title span:after {content:")";}\
  806. \
  807. @-webkit-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  808. @-moz-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  809. @keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  810. \
  811. .instant-youtube-container:not(:hover) .instant-youtube-title[hidden] {display:none; margin:0;}\
  812. .instant-youtube-container .instant-youtube-title:hover {text-decoration:underline;}\
  813. .instant-youtube-container .instant-youtube-title strong {color:white;}\
  814. \
  815. .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;}\
  816. .instant-youtube-container .instant-youtube-options-button:hover {opacity:1; background:rgba(0,0,0,0.5);}\
  817. \
  818. .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;}\
  819. .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;}\
  820. .instant-youtube-container .instant-youtube-options > label {margin-top:1ex;}\
  821. .instant-youtube-container .instant-youtube-options > label > * {display:inline;}\
  822. .instant-youtube-container .instant-youtube-options select {-webkit-appearance:menulist;}\
  823. .instant-youtube-container .instant-youtube-options [data-action="size-custom"] input {width:9ex; border:1px solid #666; padding:.5ex .5ex .4ex;}\
  824. .instant-youtube-container .instant-youtube-options [data-action="buttons"] {margin-top:1em;}\
  825. .instant-youtube-container .instant-youtube-options button {padding:.5ex 2ex; margin:0 1ex 0 0; border:2px solid gray; font-weight:bold;}\
  826. .instant-youtube-container .instant-youtube-options button:hover {border-color:white;}\
  827. .instant-youtube-container .instant-youtube-options > [disabled] {opacity:0.25;}\
  828. \
  829. .instant-youtube-container .instant-youtube-storyboard {position:absolute; display:flex; flex-direction:row; left:0; right:0; bottom:10px; max-height:33%; transition:opacity 1s ease; opacity:0;}\
  830. .instant-youtube-container:hover .instant-youtube-storyboard {opacity:1;}\
  831. .instant-youtube-container .instant-youtube-storyboard div {flex:auto;}\
  832. .instant-youtube-container .instant-youtube-storyboard img {border:3px solid rgba(255,255,255,.5); box-shadow:2px 2px 10px black; max-height:100%; width:auto!important;}\
  833. '));
  834. }