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. Optionally a fast simple HTML5 direct playback (720p max) can be selected if available for the video.

当前为 2019-07-27 提交的版本,查看 最新版本

  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. Optionally a fast simple HTML5 direct playback (720p max) can be selected if available for the video.
  4. // @description:ru На порядок ускоряет время загрузки страниц с большим количеством вставленных Youtube-видео. С первого момента загрузки страницы появляются заглушки для видео, которые можно щелкнуть для загрузки плеера, и почти сразу же появляются кавер-картинки с названием видео. В опциях можно включить режим использования упрощенного браузерного плеера (макс. 720p).
  5. // @version 2.9.14
  6. // @include *
  7. // @exclude /^https:\/\/(www\.)?youtube\.com\/(?!embed)/
  8. // @exclude https://accounts.google.*/o/oauth2/postmessageRelay*
  9. // @exclude https://clients*.google.*/youtubei/*
  10. // @exclude https://clients*.google.*/static/proxy*
  11. // @author wOxxOm
  12. // @namespace wOxxOm.scripts
  13. // @license MIT License
  14. // @grant GM_getValue
  15. // @grant GM_listValues
  16. // @grant GM_deleteValue
  17. // @grant GM_setValue
  18. // @grant GM_addStyle
  19. // @grant GM_xmlhttpRequest
  20. // @connect www.youtube.com
  21. // @connect youtube.com
  22. // @run-at document-start
  23. // @icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACABAMAAAAxEHz4AAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAwUExURUxpcQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJuxkb8AAAAPdFJOUwDvH0biMvjOZFW6pxJ6kh7r3iMAAAPDSURBVGje7ZlNaBNBFMeXhNDWpkKgFg9iYlBB6SGwiPQkftaCYATjTaRKiwi1xVaKXpqTpHhosR66p4pQhb209CQGbSweK/TiRYwfFy+NkWBM2pR2nHm73abJzuceRMj/kEzSvl92Z9689+atpjXUUEMN1WgpoRupbH41nTbNUaxzlkIhe0C+M810Ov8zmzL0RGeNeeDThUEkof72N/Fqe/8LJK07sR173yJS0EbEATxFSurZtm9DilqxAV9VAZuWfbPbLBOFqtSBP9f/WxIAV2Bc6H5owiKPG7p+IpFIRG11LsPbEfyVrhvTqeyX1dfmaBiM9gFgjgwrTzJSfncMFq7s3EExJuu5/rHte3hPBvfkff84sbuEBxPkUiLygCC5hDV7CvpUtt81axICZBN9UwHsxYalOMxhIaIC8IVhFlvJtlALIWQl57Um/LquBpjBpkOwin1qADKLB7RD9moqiPz2TcAMqQGa4OI9Av5op/DrMzXAHmz6mw4IxEQA67AW825/bhngAVoBMEHzZD+aFQCsQUCkAAor/M2wCYAVdwCqxJmANgD8cmJjPQDt5wK22AD0nAVoBsAiE1BMcgAbAJikAqoTYP1CA4BEtBgdgC6yARUuAC3QI7sDiLMAxUk2YAwiIwNAn4YAhGU+YKcOqAUMCgJQziugHGMALmNAhANAWxkaoEgABS4ADdMyiyiglPMIcJ0GKQAayDAAGQEAuu8VUB/gJAH1AS4IgLAwAA24AAoygAeuAPFbqHPHoNwc1HuCJCDncRl7NG8At7Ak48qugVEGsOBxO7snB58T0ngASlwWjomFpMegOusxrFOLBCexsFMbvUzxCyVXRqEkBpjlpXdOgcEqFlsEKpRynFviMIus0md+kcUEDAuUeaxCcysjUGgySt1yTKTUZRTbOaFim17unxUr92doBw4f9zTKObGInZl+//NTW592VP3g+Q4Onh6Ovjfgt5vsPoSCJuDuPRz/58CFmhEtKPIEvY8kZAd3VxRxRJJSyIXcUu0/VOz3okITJRC2ex9kGdB5ecBVZLtgCyt70fUB2nGTTjOu/HFZohsXXLoOrbQKfDps1ePtTj9wSter2oGWoBnYRZqB+bQ5OnLaShpnrNAz6N6R7OW1I1HJjnmPVFuit7eDV1jNvuAkpJNqgJ0DQPCHiv3dqmULfJe3P7hrB/oej3T0S/Tme7tf1Xp/MArPB/Ayp82X5OlAaJfI8wHsJ2/zWXg6EGV4XXB5CbuN3mUYxnQKNI6HU9i3op0y3tpQQw39b/oLfDt0HcsiqWsAAAAASUVORK5CYII=
  24. // @compatible chrome
  25. // @compatible firefox
  26. // @compatible opera
  27. // ==/UserScript==
  28.  
  29. 'use strict';
  30.  
  31. // keep video info cache for a month since last time it's shown
  32. var CACHE_STALE_DURATION = 30 * 24 * 3600e3;
  33.  
  34. var playQuality = GM_getValue('quality', 'auto') || 'auto';
  35.  
  36. if (/^https:\/\/(www\.)?youtube\.com\//.test(location)) {
  37. if (playQuality !== 'auto') {
  38. window.addEventListener('load', function _() {
  39. window.removeEventListener('load', _);
  40. var player = $('.html5-video-player');
  41. if (player && typeof player.setPlaybackQuality === 'function')
  42. player.setPlaybackQuality(playQuality);
  43. });
  44. }
  45. if (!window.chrome || window === window.parent)
  46. return;
  47. parent.postMessage('FYTE-toggle-fullscreen-init', '*');
  48. addEventListener('message', function onMessage(e) {
  49. if (e.source !== parent || e.data !== 'FYTE-toggle-fullscreen-init-confirmed')
  50. return;
  51. removeEventListener('message', onMessage);
  52. var fsbtn = document.getElementsByClassName('ytp-fullscreen-button');
  53. new MutationObserver(function() {
  54. if (fsbtn[0]) {
  55. this.disconnect();
  56. // noinspection SillyAssignmentJS
  57. fsbtn[0].outerHTML = fsbtn[0].outerHTML.replace('aria-disabled="true"', '');
  58. fsbtn[0].addEventListener('click', function() {
  59. window.parent.postMessage('FYTE-toggle-fullscreen', '*');
  60. });
  61. }
  62. }).observe(document, {subtree:true, childList:true});
  63. });
  64. return;
  65. }
  66.  
  67. var resizeMode = GM_getValue('resize', 'Fit to width');
  68. if (typeof resizeMode !== 'string')
  69. resizeMode = resizeMode ? 'Fit to width' : 'Original';
  70.  
  71. var resizeWidth = GM_getValue('width', 1280) |0;
  72. var resizeHeight = GM_getValue('height', 720) |0;
  73. updateCustomSize();
  74.  
  75. var pinnedWidth = GM_getValue('pinnedWidth', 400) |0;
  76.  
  77. var playDirectly = !!GM_getValue('playHTML5', false);
  78. var playDirectlyShown = !!GM_getValue('playHTML5shown', false);
  79. var skipCustom = !!GM_getValue('skipCustom', true);
  80. var showStoryboard = !!GM_getValue('showStoryboard', true);
  81. var pinnable = GM_getValue('pinnable', 'on');
  82. if (!/^(on|hide|off)$/.test(pinnable))
  83. pinnable = !!pinnable ? 'on' : 'hide';
  84.  
  85. var _ = initTL();
  86.  
  87. var imageLoader = document.createElement('img');
  88. var imageLoader2 = document.createElement('img');
  89.  
  90. var fytedom = document.getElementsByClassName('instant-youtube-container');
  91. var iframes = document.getElementsByTagName('iframe');
  92. var objects = document.getElementsByTagName('object');
  93. var checked = [];
  94. var persite = (function() {
  95. var rules = [
  96. {host: 'developers.google.com',
  97. match: '[data-video-id]',
  98. src: function(e) { return '//youtube.com/embed/' + e.dataset.videoId }},
  99. {host: 'play.google.com', eatparent: 0},
  100. {host: /(^|\.)google\.\w{2,3}(\.\w{2,3})?$/, class:'g-blk', query: 'a[href*="youtube.com/watch"][data-ved]', eatparent: 1},
  101. {host: 'pikabu.ru', class:'b-video', match: '[data-url*="youtube.com/embed"]', attr: 'data-url'},
  102. {host: 'androidauthority.com', eatparent: '.video-container'},
  103. {host: 'reddit.com',
  104. match: '[data-url*="youtube.com/"] [src*="/mediaembed"], [data-url*="youtu.be/"] [src*="/mediaembed"]',
  105. src: function(e) { return e.closest('[data-url*="youtube.com/"], [data-url*="youtu.be/"]').dataset.url }},
  106. {host: /(www\.)?theverge\.com$/, eatparent: '.p-scalable-video'},
  107. {host: '9gag.com', eatparent: 0},
  108. {host: 'reddit.com', match: '[data-url*="youtube.com"] iframe[src*="redditmedia.com/mediaembed"]',
  109. src: function(e) { return e.closest('[data-url*="youtube.com"]').dataset.url }},
  110. {host: 'anilist.co', eatparent: '.youtube'},
  111. ];
  112. for (var i=0, rule; (i<rules.length) && (rule=rules[i]); i++) {
  113. var rx = rule.host instanceof RegExp ? rule.host : new RegExp('(^|\\.)' + rule.host.replace(/\./g, '\\.') + '$', 'i');
  114. if (rx.test(location.hostname)) {
  115. if (!rule.tag && !rule.class)
  116. rule.tag = 'iframe';
  117. if (!rule.match && !rule.query)
  118. rule.match = '[src*="youtube.com/embed"]';
  119. return {
  120. nodes: rule.class ? document.getElementsByClassName(rule.class) : document.getElementsByTagName(rule.tag),
  121. match: rule.match ?
  122. function(e) {
  123. // noinspection JSReferencingMutableVariableFromClosure
  124. return e.matches(rule.match) ? e : null;
  125. } :
  126. function(e) {
  127. // noinspection JSReferencingMutableVariableFromClosure
  128. return e.querySelector(rule.query);
  129. },
  130. attr: rule.attr,
  131. src: rule.src,
  132. eatparent: rule.eatparent,
  133. };
  134. }
  135. }
  136. })();
  137.  
  138. findEmbeds([]);
  139. injectStylesIfNeeded();
  140. new MutationObserver(findEmbeds).observe(document, {subtree:true, childList:true});
  141.  
  142. document.addEventListener('DOMContentLoaded', function(e) {
  143. injectStylesIfNeeded();
  144. adjustNodesIfNeeded(e);
  145. setTimeout(cleanupCache, 60e3);
  146. });
  147.  
  148. window.addEventListener('resize', adjustNodesIfNeeded, true);
  149.  
  150. window.addEventListener('message', function(e) {
  151. switch (e.data) {
  152. case 'FYTE-toggle-fullscreen-init':
  153. e.source.postMessage('FYTE-toggle-fullscreen-init-confirmed', '*');
  154. break;
  155. case 'FYTE-toggle-fullscreen':
  156. $$('iframe[allowfullscreen]').some(function (iframe) {
  157. if (iframe.contentWindow === e.source) {
  158. goFullscreen(iframe, !(document.webkitIsFullScreen || document.mozIsFullScreen || document.isFullScreen));
  159. return true;
  160. }
  161. });
  162. break;
  163. case 'iframe-allowfs':
  164. $$('iframe:not([allowfullscreen])').some(function (iframe) {
  165. if (iframe.contentWindow === e.source) {
  166. iframe.allowFullscreen = true;
  167. return true;
  168. }
  169. });
  170. if (window !== window.top)
  171. window.parent.postMessage('iframe-allowfs', '*');
  172. break;
  173. }
  174. });
  175.  
  176. function findEmbeds(mutations) {
  177. var i, len, e, m;
  178. if (mutations.length === 1) {
  179. var added = mutations[0].addedNodes;
  180. if (!added[0] || !added[1] && added[0].nodeType === 3)
  181. return;
  182. }
  183. if (persite)
  184. for (i=0, len=persite.nodes.length; (i<len) && (e=persite.nodes[i]); i++)
  185. if ((e = persite.match(e)))
  186. processEmbed(e, persite.src && persite.src(e) || e.getAttribute(persite.attr));
  187. for (i=0, len=iframes.length; (i<len) && (e=iframes[i]); i++) {
  188. if (checked.includes(e)) continue;
  189. checked.push(e);
  190. if (/youtube\.com|youtu\.be/i.test(e.src || e.dataset.src))
  191. processEmbed(e, e.src || e.dataset.src);
  192. }
  193. for (i=0, len=objects.length; (i<len) && (e=objects[i]); i++) {
  194. if (checked.includes(e)) continue;
  195. checked.push(e);
  196. if ((m = e.querySelector('embed, [value*="youtu.be"], [value*="youtube.com"]')))
  197. processEmbed(e, m.src || e.dataset.src || 'https://' + m.value.match(/youtu\.be.*|youtube\.com.*/)[0]);
  198. }
  199. }
  200.  
  201. function processEmbed(node, src) {
  202. function decodeEmbedUrl(url) {
  203. return url.indexOf('youtube.com%2Fembed') > 0
  204. ? decodeURIComponent(url.replace(/^.*?(http[^&?=]+?youtube.com%2Fembed[^&]+).*$/i, '$1'))
  205. : url;
  206. }
  207. src = src || node.src || node.href || '';
  208. var n = node;
  209. var np = n.parentNode;
  210. var srcFixed = decodeEmbedUrl(src).replace(/\/(watch\?v=|v\/)/, '/embed/').replace(/^([^?&]+)&/, '$1?');
  211. if (src.indexOf('cdn.embedly.com/') > 0 ||
  212. resizeMode !== 'Original' && np && np.children.length === 1 && !np.className && !np.id)
  213. {
  214. n = location.hostname === 'disqus.com' ? np.parentNode : np;
  215. np = n.parentElement;
  216. }
  217. if (!np ||
  218. !np.parentNode ||
  219. skipCustom && srcFixed.indexOf('enablejsapi=1') > 0 ||
  220. node.matches('.instant-youtube-embed, .YTLT-embed') ||
  221. srcFixed.indexOf('/embed/videoseries') > 0 ||
  222. node.onload // skip some retarded loaders
  223. )
  224. return;
  225.  
  226. var id = srcFixed.match(/(?:^(?:https?:)?\/\/)(?:www\.)?(?:youtube\.com\/(?:embed\/(?:v=)?|\/.*?[&?\/]v[=\/])|youtu\.be\/)([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
  227. if (!id)
  228. return;
  229. id = id[1];
  230.  
  231. var autoplay = srcFixed.indexOf('autoplay=1') > 0;
  232.  
  233. if (np.localName === 'object')
  234. n = np, np = n.parentElement;
  235.  
  236. var eatparent = persite && persite.eatparent || 0;
  237. if (typeof eatparent === 'string')
  238. n = np.closest(eatparent) || n, np = n.parentElement;
  239. else
  240. while (eatparent--)
  241. n = np, np = n.parentElement;
  242.  
  243. injectStylesIfNeeded('force');
  244.  
  245. var div = document.createElement('div');
  246. div.className = 'instant-youtube-container';
  247. div.FYTE = {
  248. state: 'querying',
  249. srcEmbed: srcFixed.replace(/&$/, ''),
  250. originalWidth: /%/.test(node.width) ? 320 : node.width|0 || n.clientWidth|0,
  251. originalHeight: /%/.test(node.height) ? 200 : node.height|0 || n.clientHeight|0,
  252. cache: tryJSONparse(localStorage['FYTE-cache-' + id]) || {
  253. id: id,
  254. }
  255. };
  256. div.FYTE.srcEmbedFixed = div.FYTE.srcEmbed.replace(/^http:/, 'https:').replace(/([&?])(wmode=\w+|feature=oembed)&?/, '$1').replace(/[&?]$/, '');
  257. div.FYTE.srcWatchFixed = div.FYTE.srcEmbedFixed.replace(/\/embed\//, '/watch?v=').replace(/(\?.*?)\?/, '$1&');
  258.  
  259. var cache = div.FYTE.cache;
  260. cache.lastUsed = Date.now();
  261. localStorage['FYTE-cache-' + id] = JSON.stringify(cache);
  262.  
  263. if (cache.reason)
  264. div.setAttribute('disabled', '');
  265.  
  266. var divSize = calcContainerSize(div, n);
  267. var origStyle = getComputedStyle(n);
  268. div.style.cssText = important(
  269. (autoplay ? '' : 'background-color:transparent; transition:background-color 2s;') +
  270. (origStyle.hasOwnProperty('position') ? Object.keys(origStyle) : Object.keys(origStyle.__proto__) /*FF*/)
  271. .filter(function(k) { return !!k.match(/^(position|left|right|top|bottom)$/) })
  272. .map(function(k) { return k + ':' + origStyle[k] })
  273. .join(';')
  274. .replace(/\b[^;:]+:\s*(auto|static|block)\s*(!\s*important)?;/g, '') +
  275. (origStyle.display === 'inline' ? ';display:inline-block;width:100%' : '') +
  276. ';min-width:' + Math.min(divSize.w, div.FYTE.originalWidth) + 'px' +
  277. ';min-height:' + Math.min(divSize.h, div.FYTE.originalHeight) + 'px' +
  278. (resizeMode === 'Fit to width' ? ';width:100%' : '') +
  279. ';max-width:' + divSize.w + 'px; height:' + (persite && persite.eatparent === 0 ? '100%;' : divSize.h + 'px;'));
  280. if (!autoplay) {
  281. setTimeout(function() { div.style.backgroundColor = '' }, 0);
  282. setTimeout(function() { div.style.transition = '' }, 2000);
  283. }
  284.  
  285. // consume parents of retardedly positioned videos
  286. var parentStyle = getComputedStyle(np);
  287. if (div.style.position.match('absolute|relative')
  288. && parseFloat(parentStyle.paddingTop) + parseFloat(parentStyle.paddingBottom) < parseFloat(parentStyle.height)) {
  289. if (np.children.length === 1 &&
  290. floatPadding(np, parentStyle, 'Top') >= div.FYTE.originalHeight-1 ||
  291. floatPadding(np, getComputedStyle(np, ':after'), 'Top') >= div.FYTE.originalHeight-1
  292. ) {
  293. n = np, np = n.parentElement;
  294. }
  295. div.style.cssText = div.style.cssText.replace(/\b(position|left|top|right|bottom):[^;]+/g, '');
  296. }
  297.  
  298. var wrapper = div.appendChild(document.createElement('div'));
  299. wrapper.className = 'instant-youtube-wrapper';
  300.  
  301. var img = wrapper.appendChild(document.createElement('img'));
  302. if (!autoplay)
  303. img.src = 'https://i.ytimg.com/vi/' + id + '/' + (cache.cover || 'maxresdefault.jpg');
  304. img.className = 'instant-youtube-thumbnail';
  305. img.style.cssText = important((cache.cover ? '' : 'transition:opacity 0.1s ease-out; opacity:0; ') +
  306. 'padding:0; margin:auto; position:absolute; left:0; right:0; top:0; bottom:0; max-width:none; max-height:none;');
  307.  
  308. img.onload = function(e) {
  309. if (img.naturalWidth <= 120 && !cache.cover)
  310. return img.onerror(e);
  311. var fitToWidth = true;
  312. if (img.naturalHeight || cache.coverHeight) {
  313. if (!cache.coverHeight) {
  314. cache.coverWidth = img.naturalWidth;
  315. cache.coverHeight = img.naturalHeight;
  316. localStorage['FYTE-cache-' + id] = JSON.stringify(cache);
  317. }
  318. var ratio = cache.coverWidth / cache.coverHeight;
  319. if (ratio > 4.1/3 && ratio < divSize.w/divSize.h) {
  320. img.style.cssText += important('width:auto; height:100%;');
  321. fitToWidth = false;
  322. }
  323. }
  324. if (fitToWidth) {
  325. img.style.cssText += important('width:100%; height:auto;');
  326. }
  327. if (cache.videoWidth)
  328. fixThumbnailAR(div);
  329. if (!autoplay)
  330. img.style.opacity = 1;
  331. };
  332. img.onerror = function() {
  333. if (img.src.indexOf('maxresdefault') > 0)
  334. img.src = img.src.replace('maxresdefault','sddefault');
  335. else if (img.src.indexOf('sddefault') > 0)
  336. img.src = img.src.replace('sddefault','hqdefault');
  337. };
  338. if (cache.coverWidth)
  339. img.onload();
  340.  
  341. translateHTML(wrapper, 'beforeend', '\
  342. <a class="instant-youtube-title" target="_blank" href="' + div.FYTE.srcWatchFixed + '">' +
  343. (cache.title || cache.reason ? '<strong>' + (cache.title || cache.reason || '') + '</strong>' +
  344. (cache.duration ? '<span>' + cache.duration + '</span>' : '') +
  345. (cache.fps ? '<i>, ' + cache.fps + 'fps</i>' : '')
  346. : '&nbsp;') + '</a>\
  347. <svg class="instant-youtube-play-button">\
  348. <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">\
  349. <title tl>msgAltPlayerHint</title>\
  350. </path>\
  351. <polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" points="33.3,41.4 33.3,17.75 56,29.6"></polygon>\
  352. </svg>\
  353. <span tl class="instant-youtube-alternative">' + (playDirectly ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  354. <div tl class="instant-youtube-options-button">Options</div>\
  355. ');
  356.  
  357. np.insertBefore(div, n);
  358. n.remove();
  359.  
  360. if (!cache.title && !cache.reason || autoplay && playDirectly)
  361. fetchInfo();
  362.  
  363. if (autoplay)
  364. return startPlaying(div);
  365.  
  366. div.addEventListener('click', clickHandler);
  367. div.addEventListener('mousedown', clickHandler);
  368. div.addEventListener('mouseenter', fetchInfo);
  369.  
  370. function fetchInfo() {
  371. div.removeEventListener('mouseenter', fetchInfo);
  372. if (!div.FYTE.storyboard) {
  373. GM_xmlhttpRequest({
  374. method: 'GET',
  375. url: 'https://www.youtube.com/get_video_info?video_id=' + id +
  376. '&hl=en_US&html5=1&el=embedded&eurl=' + encodeURIComponent(location.href),
  377. context: div,
  378. onload: parseVideoInfo
  379. });
  380. }
  381. }
  382. }
  383.  
  384. function adjustNodesIfNeeded(e) {
  385. if (!fytedom[0])
  386. return;
  387. if (adjustNodesIfNeeded.scheduled)
  388. clearTimeout(adjustNodesIfNeeded.scheduled);
  389. adjustNodesIfNeeded.scheduled = setTimeout(function() {
  390. adjustNodes(e);
  391. adjustNodesIfNeeded.scheduled = 0;
  392. }, 16);
  393. }
  394.  
  395. function adjustNodes(e, clickedContainer) {
  396. var force = !!clickedContainer;
  397. var nearest = force ? clickedContainer : null;
  398.  
  399. var vids = $$('.instant-youtube-container:not([pinned]):not([stub])');
  400.  
  401. if (!nearest && e.type !== 'DOMContentLoaded') {
  402. var minDistance = window.innerHeight*3/4 |0;
  403. var nearTargetY = window.innerHeight/2;
  404. vids.forEach(function(n) {
  405. var bounds = n.getBoundingClientRect();
  406. var distance = Math.abs((bounds.bottom + bounds.top)/2 - nearTargetY);
  407. if (distance < minDistance) {
  408. minDistance = distance;
  409. nearest = n;
  410. }
  411. });
  412. }
  413.  
  414. if (nearest) {
  415. var bounds = nearest.getBoundingClientRect();
  416. var nearestCenterYpct = (bounds.top + bounds.bottom)/2 / window.innerHeight;
  417. }
  418.  
  419. var resized = false;
  420.  
  421. vids.forEach(function(n) {
  422. var size = calcContainerSize(n);
  423. var w = size.w, h = size.h;
  424.  
  425. // prevent parent clipping
  426. for (var e=n.parentElement, style; e; e=e.parentElement)
  427. if (e.style.overflow !== 'visible' && (style=getComputedStyle(e)))
  428. if ((style.overflow+style.overflowX+style.overflowY).match(/hidden|scroll/))
  429. if (n.offsetTop < e.clientHeight / 2 && n.offsetTop + n.clientHeight > e.clientHeight)
  430. e.style.cssText = e.style.cssText.replace(/\boverflow(-[xy])?:[^;]+/g, '') +
  431. important('overflow:visible;overflow-x:visible;overflow-y:visible;');
  432.  
  433. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  434. return;
  435.  
  436. if (n.style.maxWidth !== w + 'px') overrideCSS(n, {'max-width': w + 'px'});
  437. if (n.style.height !== h + 'px') overrideCSS(n, {'height': h + 'px'});
  438. if (parseFloat(n.style.minWidth) > w) overrideCSS(n, {'min-width': n.style.maxWidth});
  439. if (parseFloat(n.style.minHeight) > h) overrideCSS(n, {'min-height': n.style.height});
  440.  
  441. fixThumbnailAR(n);
  442. resized = true;
  443. });
  444.  
  445. if (resized && nearest)
  446. setTimeout(function() {
  447. var bounds = nearest.getBoundingClientRect();
  448. var h = bounds.bottom - bounds.top;
  449. var projectedCenterY = nearestCenterYpct * window.innerHeight;
  450. var projectedTop = projectedCenterY - h/2;
  451. var safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  452. window.scrollBy(0, bounds.top - safeTop);
  453. }, 16);
  454. }
  455.  
  456. function calcContainerSize(div, origNode) {
  457. origNode = origNode || div;
  458. var w, h;
  459. var np = origNode.parentElement;
  460. var style = getComputedStyle(np);
  461. var parentWidth = parseFloat(style.width) - floatPadding(np, style, 'Left') - floatPadding(np, style, 'Right');
  462. if (+style.columnCount > 1)
  463. parentWidth = (parentWidth + parseFloat(style.columnGap)) / style.columnCount - parseFloat(style.columnGap);
  464. switch (resizeMode) {
  465. case 'Original':
  466. if (div.FYTE.originalWidth === 320 && div.FYTE.originalHeight === 200) {
  467. w = parentWidth;
  468. h = parentWidth / 16 * 9;
  469. } else {
  470. w = div.FYTE.originalWidth;
  471. h = div.FYTE.originalHeight;
  472. }
  473. break;
  474. case 'Custom':
  475. w = resizeWidth;
  476. h = resizeHeight;
  477. break;
  478. case '1080p':
  479. case '720p':
  480. case '480p':
  481. case '360p':
  482. h = parseInt(resizeMode);
  483. w = h / 9 * 16;
  484. break;
  485. default: // fit-to-width mode
  486. var n = origNode;
  487. do {
  488. n = n.parentElement;
  489. // find parent node with nonzero width (i.e. independent of our video element)
  490. } while (n && !(w = n.clientWidth));
  491. if (w)
  492. h = w / 16 * 9;
  493. else {
  494. w = origNode.clientWidth;
  495. h = origNode.clientHeight;
  496. }
  497. }
  498. if (parentWidth > 0 && parentWidth < w) {
  499. h = parentWidth / w * h;
  500. w = parentWidth;
  501. }
  502. if (resizeMode === 'Fit to width' && h < div.FYTE.originalHeight*0.9)
  503. h = Math.min(div.FYTE.originalHeight, w / div.FYTE.originalWidth * div.FYTE.originalHeight);
  504.  
  505. return {w: window.chrome ? w : Math.round(w), h:h};
  506. }
  507.  
  508. function parseVideoInfo(response) {
  509. var div = response.context;
  510. var txt = response.responseText;
  511. var info = tryCatch(function() {
  512. var json = txt.replace(/(\w+)=?(.*?)(&|$)/g, '"$1":"$2",').replace(/^(.+?),?$/, '{$1}');
  513. return tryJSONparse(json);
  514. }) || {};
  515. var cache = div.FYTE.cache;
  516. var shouldUpdateCache = false;
  517. var videoSources = [];
  518.  
  519. // parse width & height to adjust the thumbnail
  520. var m = decodeURIComponent(info.adaptive_fmts || '').match(/size=(\d+)x(\d+)\b/) ||
  521. decodeURIComponent(txt).match(/\/(\d+)x(\d+)\//);
  522.  
  523. if (m && (cache.videoWidth !== (m[1]|0) || cache.videoHeight !== (m[2]|0))) {
  524. fixThumbnailAR(div, m[1]|0, m[2]|0);
  525. cache.videoWidth = m[1]|0;
  526. cache.videoHeight = m[2]|0;
  527. shouldUpdateCache = true;
  528. }
  529.  
  530. // parse video sources
  531. if (info.url_encoded_fmt_stream_map && info.fmt_list) {
  532. var streams = {};
  533. decodeURIComponent(info.url_encoded_fmt_stream_map).split(',').forEach(function(stream) {
  534. var params = {};
  535. stream.split('&').forEach(function(kv) {
  536. params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
  537. });
  538. streams[params.itag] = params;
  539. });
  540. decodeURIComponent(info.fmt_list).split(',').forEach(function(fmt) {
  541. var itag = fmt.split('/')[0];
  542. var dimensions = fmt.split('/')[1];
  543. var stream = streams[itag];
  544. if (stream) {
  545. videoSources.push({
  546. src: stream.url + (stream.s ? '&signature=' + stream.s : ''),
  547. title: stream.quality + ', ' + dimensions + ', ' + stream.type
  548. });
  549. }
  550. });
  551. } else {
  552. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  553. var text = decodeURIComponent(txt).split('url_encoded_fmt_stream_map')[1];
  554. while ((m = rx.exec(text))) {
  555. videoSources.push({
  556. src: decodeURIComponent(decodeURIComponent(m[1]))
  557. });
  558. }
  559. }
  560.  
  561. var fps = {};
  562. (decodeURIComponent(info.adaptive_fmts || ''))
  563. .split(',')
  564. .filter(function(s) { return /(^|&)type=video/.test(s) && /\b(?:fps=)([\d.]+)/.test(s) })
  565. .forEach(function(s) { fps[s.match(/\b(?:fps=)([\d.]+)/)[1]] = true });
  566. fps = Object.keys(fps).join('/');
  567. if (fps && cache.fps !== fps) {
  568. cache.fps = fps;
  569. shouldUpdateCache = true;
  570. }
  571.  
  572. var duration = div.FYTE.duration = info.length_seconds|0 || '';
  573. if (duration) {
  574. var d = new Date(null);
  575. d.setSeconds(duration);
  576. duration = d.toISOString().replace(/^.+?T[0:]{0,4}(.+?)\..+$/, '$1');
  577. if (cache.duration !== duration) {
  578. cache.duration = duration;
  579. shouldUpdateCache = true;
  580. }
  581. }
  582. if (duration || fps)
  583. duration = '<span>' + duration + '</span>' +
  584. (fps ? '<i>, ' + fps + 'fps</i>' : '');
  585.  
  586. var title = decodeURIComponent(info.title || info.reason || '').replace(/\+/g, ' ');
  587. if (title) {
  588. $(div, '.instant-youtube-title').innerHTML = (title ? '<strong>' + title + '</strong>' : '') + duration;
  589. if (cache.title !== title) {
  590. cache.title = title;
  591. shouldUpdateCache = true;
  592. }
  593. }
  594. if (pinnable !== 'off' && info.title)
  595. makeDraggable(div);
  596.  
  597. if (info.reason) {
  598. div.setAttribute('disabled', '');
  599. if (cache.reason !== info.reason) {
  600. cache.reason = info.reason;
  601. shouldUpdateCache = true;
  602. }
  603. }
  604.  
  605. if (videoSources.length)
  606. div.FYTE.videoSources = videoSources;
  607.  
  608. if (info.storyboard_spec && div.FYTE.state !== 'scheduled play') {
  609. m = decodeURIComponent(decodeURIComponent(info.storyboard_spec)).split('|');
  610. div.FYTE.storyboard = tryJSONparse(
  611. m[m.length-1].replace(
  612. /^(\d+)#(\d+)#(\d+)#(\d+)#(\d+)#.+$/,
  613. '{"w":$1, "h":$2, "len":$3, "rows":$4, "cols":$5}'
  614. ));
  615. if (div.FYTE.storyboard.w * div.FYTE.storyboard.h > 2000) {
  616. div.FYTE.storyboard.url = m[0].replace('?', '&').replace('$L/$N.jpg',
  617. (m.length-2) + '/M0.jpg?sigh=' + m[m.length-1].replace(/^.+?#([^#]+)$/, '$1'));
  618. $(div, '.instant-youtube-options-button').insertAdjacentHTML('beforebegin',
  619. '<div class="instant-youtube-storyboard"' + (showStoryboard ? '' : ' disabled') + '>' +
  620. important('<div style="width:' + (div.FYTE.storyboard.w-1) + 'px; height:' + div.FYTE.storyboard.h + 'px;') +
  621. '">&nbsp;</div>' +
  622. '</div>');
  623. if (showStoryboard)
  624. updateHoverHandler(div);
  625. }
  626. }
  627.  
  628. injectStylesIfNeeded();
  629.  
  630. if (div.FYTE.state === 'scheduled play')
  631. setTimeout(function() { startPlayingDirectly(div) }, 0);
  632.  
  633. div.FYTE.state = '';
  634.  
  635. var cover = decodeURIComponent(info.iurlmaxres || info.iurlhq || info.iurl || '').match(/[^\/]+$/);
  636. if (cover && cache.cover !== cover[0]) {
  637. cache.cover = cover[0];
  638. shouldUpdateCache = true;
  639. }
  640. if (shouldUpdateCache)
  641. localStorage['FYTE-cache-' + info.video_id] = JSON.stringify(cache);
  642. }
  643.  
  644. function fixThumbnailAR(div, w, h) {
  645. var img = $(div, 'img');
  646. if (!img)
  647. return;
  648. var thw = img.naturalWidth, thh = img.naturalHeight;
  649. if (w && h) { // means thumbnail is still loading
  650. div.FYTE.cache.videoWidth = w;
  651. div.FYTE.cache.videoHeight = h;
  652. } else {
  653. w = div.FYTE.cache.videoWidth;
  654. h = div.FYTE.cache.videoHeight;
  655. if (!w || !h)
  656. return;
  657. }
  658. var divw = div.clientWidth, divh = div.clientHeight;
  659. // if both video and thumbnail are 4:3, fit the image to height
  660. //console.log(div, divw, divh, thw, thh, w, h, h/w*divw / divh - 1, thh/thw*divw / divh - 1);
  661. if (Math.abs(h/w*divw / divh - 1) > 0.05 && Math.abs(thh/thw*divw / divh - 1) > 0.05) {
  662. img.style.maxHeight = img.clientHeight + 'px';
  663. if (!div.FYTE.cache.videoWidth) // skip animation if thumbnail is already loaded
  664. img.style.transition = 'height 1s ease, margin-top 1s ease';
  665. setTimeout(function() {
  666. img.style.maxHeight = 'none';
  667. img.style.cssText += important(h/w >= divh/divw ? 'width:auto; height:100%;' : 'width:100%; height:auto;');
  668. setTimeout(function() {
  669. img.style.transition = '';
  670. }, 1000);
  671. }, 0);
  672. }
  673. }
  674.  
  675. function updateHoverHandler(div) {
  676. var sb = $(div, '.instant-youtube-storyboard');
  677. if (!showStoryboard) {
  678. if (!sb.getAttribute('disabled'))
  679. sb.setAttribute('disabled', '');
  680. return;
  681. }
  682. if (sb.hasAttribute('disabled'))
  683. sb.removeAttribute('disabled');
  684.  
  685. sb.addEventListener('click', storyboardClickHandler);
  686.  
  687. var oldIndex = null;
  688. var style = sb.firstElementChild.style;
  689. sb.addEventListener('mousemove', storyboardHoverHandler);
  690. sb.addEventListener('mouseout', storyboardHoverHandler);
  691.  
  692. div.addEventListener('mouseover', storyboardPreloader);
  693. div.addEventListener('mouseout', storyboardPreloader);
  694.  
  695. var spinner = document.createElement('span');
  696. spinner.className = 'instant-youtube-loading-spinner';
  697.  
  698. function storyboardClickHandler(e) {
  699. sb.removeEventListener('click', storyboardClickHandler);
  700. var offsetX = e.offsetX || e.clientX - this.getBoundingClientRect().left;
  701. div.FYTE.startAt = offsetX / this.clientWidth * div.FYTE.duration |0;
  702. div.FYTE.srcEmbedFixed = setUrlParams(div.FYTE.srcEmbedFixed, {start: div.FYTE.startAt});
  703. startPlaying(div, {alternateMode: e.shiftKey});
  704. }
  705.  
  706. function storyboardPreloader(e) {
  707. if (e.type === 'mouseout') {
  708. imageLoader.onload = null; imageLoader.src = '';
  709. spinner.remove();
  710. return;
  711. }
  712. if (!div.FYTE.storyboard || div.FYTE.storyboard.preloaded)
  713. return;
  714. var lastpart = (div.FYTE.storyboard.len-1)/(div.FYTE.storyboard.rows * div.FYTE.storyboard.cols) |0;
  715. if (lastpart <= 0)
  716. return;
  717. var part = 0;
  718. imageLoader.src = setStoryboardUrl(part++);
  719. imageLoader.onload = function() {
  720. if (part > lastpart) {
  721. div.FYTE.storyboard.preloaded = true;
  722. div.removeEventListener('mouseover', storyboardPreloader);
  723. div.removeEventListener('mouseout', storyboardPreloader);
  724. imageLoader.onload = null;
  725. imageLoader.src = '';
  726. spinner.remove();
  727. return;
  728. }
  729. imageLoader.src = setStoryboardUrl(part++);
  730. };
  731. }
  732.  
  733. function setStoryboardUrl(part) {
  734. return div.FYTE.storyboard.url.replace(/M\d+\.jpg\?/, 'M' + part + '.jpg?');
  735. }
  736.  
  737. function storyboardHoverHandler(e) {
  738. if (!showStoryboard || !div.FYTE.storyboard)
  739. return;
  740. if (e.type === 'mouseout')
  741. return imageLoader2.onload && imageLoader2.onload();
  742. var w = div.FYTE.storyboard.w;
  743. var h = div.FYTE.storyboard.h;
  744. var cols = div.FYTE.storyboard.cols;
  745. var rows = div.FYTE.storyboard.rows;
  746. var len = div.FYTE.storyboard.len;
  747. var partlen = rows * cols;
  748.  
  749. var offsetX = e.offsetX || e.clientX - this.getBoundingClientRect().left;
  750. var left = Math.min(this.clientWidth - w, Math.max(0, offsetX - w)) |0;
  751. if (!style.left || parseInt(style.left) !== left) {
  752. style.left = left + 'px';
  753. if (spinner.parentElement)
  754. spinner.style.cssText = important('left:' + (left + w/2 - 10) + 'px; right:auto;');
  755. }
  756.  
  757. var index = Math.min(offsetX / this.clientWidth * (len+1) |0, len - 1);
  758. if (index === oldIndex)
  759. return;
  760.  
  761. var part = index/partlen|0;
  762. if (!oldIndex || part !== (oldIndex/partlen|0)) {
  763. style.cssText = style.cssText.replace(/$|background-image[^;]+;/,
  764. 'background-image: url(' + setStoryboardUrl(part) + ')!important;');
  765. if (!div.FYTE.storyboard.preloaded) {
  766. if (spinner.timer)
  767. clearTimeout(spinner.timer);
  768. spinner.timer = setTimeout(function() {
  769. spinner.timer = 0;
  770. if (!imageLoader2.src)
  771. return;
  772. this.appendChild(spinner);
  773. spinner.style.cssText = important('left:' + (left + w/2 - 10) + 'px; right:auto;');
  774. }.bind(this), 50);
  775. imageLoader2.onload = function() {
  776. clearTimeout(spinner.timer);
  777. spinner.remove();
  778. spinner.timer = 0;
  779. imageLoader2.onload = null;
  780. imageLoader2.src = '';
  781. };
  782. imageLoader2.src = setStoryboardUrl(part);
  783. }
  784. }
  785.  
  786. oldIndex = index;
  787. index = index % partlen;
  788. style.backgroundPosition = '-' + (index % cols) * w + 'px -' + (index / cols |0) * h + 'px';
  789. }
  790. }
  791.  
  792. function clickHandler(e) {
  793. if (e.target.closest('a')
  794. || e.type === 'mousedown' && e.button !== 1
  795. || e.type === 'click' && e.target.matches('.instant-youtube-options, .instant-youtube-options *'))
  796. return;
  797. if (e.type === 'click' && e.target.matches('.instant-youtube-options-button')) {
  798. showOptions(e);
  799. e.preventDefault();
  800. e.stopPropagation();
  801. return;
  802. }
  803.  
  804. e.preventDefault();
  805. e.stopPropagation();
  806. e.stopImmediatePropagation();
  807.  
  808. startPlaying(e.target.closest('.instant-youtube-container'), {
  809. alternateMode: e.shiftKey || e.target.matches('.instant-youtube-alternative'),
  810. fullscreen: e.button === 1,
  811. });
  812. }
  813.  
  814. function startPlaying(div, params) {
  815. div.removeEventListener('click', clickHandler);
  816. div.removeEventListener('mousedown', clickHandler);
  817.  
  818. $$remove(div, '.instant-youtube-alternative, .instant-youtube-storyboard, .instant-youtube-options-button, .instant-youtube-options');
  819. $(div, 'svg').outerHTML = '<span class="instant-youtube-loading-spinner"></span>';
  820.  
  821. if (pinnable !== 'off') {
  822. makePinnable(div);
  823. if (params && params.pin)
  824. $(div, '[pin="' + params.pin + '"]').click();
  825. }
  826.  
  827. if (window !== window.top)
  828. window.parent.postMessage('iframe-allowfs', '*');
  829.  
  830. if ((!!playDirectly + !!(params && params.alternateMode) === 1)
  831. && (div.FYTE.videoSources || div.FYTE.state === 'querying')) {
  832. if (div.FYTE.videoSources)
  833. startPlayingDirectly(div, params);
  834. else {
  835. // playback will start in parseVideoInfo
  836. div.FYTE.state = 'scheduled play';
  837. // fallback to iframe in 5s
  838. setTimeout(function() {
  839. if (div.FYTE.state) {
  840. div.FYTE.state = '';
  841. switchToIFrame.call(div, params);
  842. }
  843. }, 5000);
  844. }
  845. }
  846. else
  847. switchToIFrame.call(div, params);
  848. }
  849.  
  850. function startPlayingDirectly(div, params) {
  851. var video = document.createElement('video');
  852. video.controls = true;
  853. video.autoplay = true;
  854. video.style.cssText = important('position:absolute; left:0; top:0; right:0; bottom:0; padding:0; margin:auto; opacity:0; width:100%; height:100%;');
  855. video.className = 'instant-youtube-embed';
  856. video.volume = GM_getValue('volume', 0.5);
  857.  
  858. div.FYTE.videoSources.forEach(function(src) {
  859. var srcdom = video.appendChild(document.createElement('source'));
  860. Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
  861. srcdom.onerror = switchToIFrame.bind(div, params);
  862. });
  863.  
  864. overrideCSS($(div, 'img'), {transition: 'opacity 1s', opacity: '0'});
  865.  
  866. if (params && params.fullscreen) {
  867. div.firstElementChild.appendChild(video);
  868. div.setAttribute('playing', '');
  869. video.style.opacity = 1;
  870. goFullscreen(video);
  871. }
  872.  
  873. if (window.chrome && Number(navigator.userAgent.match(/Chrom\D+(\d+)|$/)[1]) < 74) {
  874. video.addEventListener('click', function onClick(debounced) {
  875. if (debounced === true)
  876. video.paused ? video.play() : video.pause();
  877. else
  878. setTimeout(onClick, 0, true);
  879. });
  880. }
  881.  
  882. var title = $(div, '.instant-youtube-title');
  883. if (title) {
  884. video.onpause = function() { title.removeAttribute('hidden') };
  885. video.onplay = function() { title.setAttribute('hidden', true) };
  886. }
  887.  
  888. var switchTimer = setTimeout(switchToIFrame.bind(div, params), 5000);
  889.  
  890. video.onloadedmetadata = div.FYTE.startAt && function() {
  891. clearTimeout(switchTimer);
  892. video.currentTime = div.FYTE.startAt;
  893. };
  894.  
  895. video.onloadeddata = function() {
  896. clearTimeout(switchTimer);
  897. pauseOtherVideos(video);
  898. video.interval = setInterval(function() {
  899. if (video.volume !== GM_getValue('volume', 0.5))
  900. GM_setValue('volume', video.volume);
  901. }, 1000);
  902. if (params && params.fullscreen)
  903. return;
  904. div.setAttribute('playing', '');
  905. div.firstElementChild.appendChild(video);
  906. video.style.opacity = 1;
  907. };
  908. }
  909.  
  910. function switchToIFrame(params, e) {
  911. if (this.querySelector('iframe'))
  912. return;
  913. var div = this;
  914. var wrapper = div.firstElementChild;
  915. var fullscreen = params && params.fullscreen && !e;
  916. if (e instanceof Event) {
  917. console.log('[FYTE] Direct linking canceled on %s, switching to IFRAME player', div.FYTE.srcEmbed);
  918. var video = e.target ? e.target.closest('video') : e.path && e.path[e.path.length-1];
  919. while (video.lastElementChild)
  920. video.lastElementChild.remove();
  921. goFullscreen(video, false);
  922. video.remove();
  923. }
  924.  
  925. var url = setUrlParams(div.FYTE.srcEmbedFixed, {
  926. html5: 1,
  927. autoplay: 1,
  928. autohide: 2,
  929. border: 0,
  930. controls: 1,
  931. fs: 1,
  932. showinfo: 1,
  933. ssl: 1,
  934. theme: 'dark',
  935. enablejsapi: 1,
  936. FYTEfullscreen: fullscreen|0,
  937. });
  938.  
  939. var iframe = document.createElement('iframe');
  940. iframe.src = url;
  941. iframe.className = 'instant-youtube-embed';
  942. iframe.style = important('position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:0;');
  943. iframe.frameBorder = 0;
  944. iframe.allow = 'autoplay; fullscreen';
  945. iframe.setAttribute('allowtransparency', 'true');
  946. iframe.setAttribute('allowfullscreen', 'true');
  947. iframe.setAttribute('width', '100%');
  948. iframe.setAttribute('height', '100%');
  949.  
  950. if (pinnable !== 'off') {
  951. var pin = $(div, '[pin]');
  952. pin.parentNode.insertBefore(iframe, pin);
  953. } else {
  954. wrapper.appendChild(iframe);
  955. }
  956.  
  957. div.setAttribute('iframe', '');
  958. div.setAttribute('playing', '');
  959.  
  960. iframe = $(div, 'iframe');
  961. if (fullscreen) {
  962. goFullscreen(iframe);
  963. iframe.style.opacity = 1;
  964. }
  965.  
  966. iframe.onload = function() {
  967. window.addEventListener('message', YTlistener);
  968. iframe.contentWindow.postMessage('{"event":"listening"}', '*');
  969. };
  970. setTimeout(function() {
  971. iframe.style.opacity = 1;
  972. window.removeEventListener('message', YTlistener);
  973. }, 5000);
  974.  
  975. function YTlistener(e) {
  976. if (e.source !== iframe.contentWindow || !e.data)
  977. return;
  978. var data = tryJSONparse(e.data);
  979. if (!data.info || data.info.playerState !== 1)
  980. return;
  981. window.removeEventListener('message', YTlistener);
  982. pauseOtherVideos(iframe);
  983. iframe.style.opacity = 1;
  984. $$remove(div, 'span, a');
  985. $(div, 'img').style.display = 'none';
  986. }
  987. }
  988.  
  989. function setUrlParams(url, params) {
  990. var names = Object.keys(params);
  991. var parts = url.split('?', 2)
  992. var query = (parts[1] || '').replace(new RegExp('(?:[?&]|^)(?:' + names.join('|') + ')(?:=[^?&]*)?', 'gi'), '');
  993. return parts[0] + '?' + query + (query ? '&' : '?') +
  994. names.map(function(n) { return n + '=' + params[n] }).join('&');
  995. }
  996.  
  997. function pauseOtherVideos(activePlayer) {
  998. $$(activePlayer.ownerDocument, '.instant-youtube-embed').forEach(function(v) {
  999. if (v === activePlayer)
  1000. return;
  1001. switch (v.localName) {
  1002. case 'video':
  1003. if (!v.paused)
  1004. v.pause();
  1005. break;
  1006. case 'iframe':
  1007. try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {}
  1008. break;
  1009. }
  1010. });
  1011. }
  1012.  
  1013. function goFullscreen(el, enable) {
  1014. if (enable !== false)
  1015. el.webkitRequestFullScreen && el.webkitRequestFullScreen()
  1016. || el.mozRequestFullScreen && el.mozRequestFullScreen()
  1017. || el.requestFullScreen && el.requestFullScreen();
  1018. else
  1019. document.webkitCancelFullScreen && document.webkitCancelFullScreen()
  1020. || document.mozCancelFullScreen && document.mozCancelFullScreen()
  1021. || document.cancelFullScreen && document.cancelFullScreen();
  1022. }
  1023.  
  1024. function makePinnable(div) {
  1025. div.firstElementChild.insertAdjacentHTML('beforeend',
  1026. '<div size-gripper></div>' +
  1027. '<div pin="top-left"></div><div pin="top-right"></div><div pin="bottom-right"></div><div pin="bottom-left"></div>');
  1028.  
  1029. $$(div, '[pin]').forEach(function(pin) {
  1030. if (pinnable === 'hide')
  1031. pin.setAttribute('transparent', '');
  1032. pin.onclick = pinClicked;
  1033. });
  1034. $(div, '[size-gripper]').addEventListener('mousedown', startResize, true);
  1035. $(div, '[size-gripper]').addEventListener('mousedown', function() { return false });
  1036.  
  1037. function pinClicked() {
  1038. var pin = this;
  1039. var pinIt = !div.hasAttribute('pinned') || !pin.hasAttribute('active');
  1040. var corner = pin.getAttribute('pin');
  1041. var video = $(div, 'video');
  1042. if (pinIt) {
  1043. $$(div, '[pin][active]').forEach(function(p) { p.removeAttribute('active') });
  1044. pin.setAttribute('active', '');
  1045. if (!div.FYTE.unpinnedStyle) {
  1046. div.FYTE.unpinnedStyle = div.style.cssText;
  1047. var stub = div.cloneNode();
  1048. var img = $(div, 'img').cloneNode();
  1049. img.style.opacity = 1;
  1050. img.style.display = 'block';
  1051. img.title = '';
  1052. stub.appendChild(img);
  1053. stub.onclick = function(e) { $(div, '[pin][active]').onclick(e) };
  1054. stub.style.cssText += 'opacity:0.3!important;';
  1055. stub.setAttribute('stub', '');
  1056. div.FYTE.stub = stub;
  1057. div.parentNode.insertBefore(stub, div);
  1058. }
  1059. var size = constrainPinnedSize(div, localStorage['width#' + location.hostname] || pinnedWidth);
  1060. div.style.cssText = important(
  1061. 'position: fixed;' +
  1062. 'width: ' + size.w + 'px;' +
  1063. 'z-index: 999999999;' +
  1064. 'height:' + size.h + 'px;' +
  1065. 'top:' + (corner.indexOf('top') >= 0 ? '0' : 'auto') + ';' +
  1066. 'bottom:' + (corner.indexOf('bottom') >= 0 ? '0' : 'auto') + ';' +
  1067. 'left:' + (corner.indexOf('left') >= 0 ? '0' : 'auto') + ';' +
  1068. 'right:' + (corner.indexOf('right') >= 0 ? '0' : 'auto') + ';'
  1069. );
  1070. adjustPinnedOffset(div, div, corner);
  1071. div.setAttribute('pinned', corner);
  1072. if (video && document.body)
  1073. document.body.appendChild(div);
  1074. }
  1075. else { // unpin
  1076. pin.removeAttribute('active');
  1077. div.removeAttribute('pinned');
  1078. div.style.cssText = div.FYTE.unpinnedStyle;
  1079. div.FYTE.unpinnedStyle = '';
  1080. if (div.FYTE.stub) {
  1081. if (video && document.body)
  1082. div.FYTE.stub.parentNode.replaceChild(div, div.FYTE.stub);
  1083. div.FYTE.stub.remove();
  1084. div.FYTE.stub = null;
  1085. }
  1086. }
  1087. if (video && video.paused)
  1088. video.play();
  1089. }
  1090.  
  1091. function startResize(e) {
  1092. var siteSaved = ('width#' + location.hostname) in localStorage;
  1093. var saveAs = siteSaved ? 'site' : 'global';
  1094. var oldSizeCSS = {w: div.style.width, h: div.style.height};
  1095. var oldDraggable = div.draggable;
  1096. div.draggable = false;
  1097.  
  1098. var gripper = this;
  1099. gripper.removeAttribute('tried-exceeding');
  1100. gripper.innerHTML = '<div>' +
  1101. '<div save-as="' + saveAs + '"><b>S</b> = Site mode: <span>' + getSiteOnlyText() + '</span></div>' +
  1102. (!siteSaved ? '' : '<div><b>R</b> = Reset to global size</div>') +
  1103. '<div><b>Esc</b> = Cancel</div>' +
  1104. '</div>';
  1105.  
  1106. document.addEventListener('mousemove', resize);
  1107. document.addEventListener('mouseup', resizeDone);
  1108. document.addEventListener('keydown', resizeKeyDown);
  1109. e.stopImmediatePropagation();
  1110. return false;
  1111.  
  1112. function getSiteOnlyText() {
  1113. return saveAs === 'site' ? 'only ' + location.hostname : 'global';
  1114. }
  1115.  
  1116. function resize(e) {
  1117. var deltaX = e.movementX || e.webkitMovementX || e.mozMovementX || 0;
  1118. if (/right/.test(div.getAttribute('pinned')))
  1119. deltaX = -deltaX;
  1120. var newSize = constrainPinnedSize(div, div.clientWidth + deltaX);
  1121. if (newSize.w !== div.clientWidth) {
  1122. div.style.setProperty('width', newSize.w + 'px', 'important');
  1123. div.style.setProperty('height', newSize.h + 'px', 'important');
  1124. gripper.removeAttribute('tried-exceeding');
  1125. } else if (newSize.triedExceeding) {
  1126. gripper.setAttribute('tried-exceeding', '');
  1127. }
  1128. window.getSelection().removeAllRanges();
  1129. return false;
  1130. }
  1131.  
  1132. function resizeDone() {
  1133. div.draggable = oldDraggable;
  1134. gripper.removeAttribute('tried-exceeding');
  1135. gripper.innerHTML = '';
  1136. document.removeEventListener('mousemove', resize);
  1137. document.removeEventListener('mouseup', resizeDone);
  1138. document.removeEventListener('keydown', resizeKeyDown);
  1139. switch (saveAs) {
  1140. case 'site':
  1141. localStorage['width#' + location.hostname] = div.clientWidth;
  1142. break;
  1143. case 'global':
  1144. pinnedWidth = div.clientWidth;
  1145. GM_setValue('pinnedWidth', pinnedWidth);
  1146. // fallthrough to remove the locally saved value
  1147. case 'reset':
  1148. localStorage.removeItem('width#' + location.hostname);
  1149. break;
  1150. case '':
  1151. return false;
  1152. }
  1153. gripper.setAttribute('saveAs', saveAs);
  1154. setTimeout(function() { gripper.removeAttribute('saveAs'); }, 250);
  1155. return false;
  1156. }
  1157.  
  1158. function resizeKeyDown(e) {
  1159. switch (e.keyCode) {
  1160. case 27: // Esc
  1161. saveAs = 'cancel';
  1162. div.style.width = oldSizeCSS.w;
  1163. div.style.height = oldSizeCSS.h;
  1164. break;
  1165. case 83: // S
  1166. saveAs = saveAs === 'site' ? 'global' : 'site';
  1167. $(gripper, '[save-as]').setAttribute('save-as', saveAs);
  1168. $(gripper, '[save-as] span').textContent = getSiteOnlyText();
  1169. return false;
  1170. case 82: // R
  1171. if (!siteSaved)
  1172. return;
  1173. saveAs = 'reset';
  1174. var size = constrainPinnedSize(div, pinnedWidth);
  1175. div.style.width = size.w;
  1176. div.style.height = size.h;
  1177. break;
  1178. default:
  1179. return;
  1180. }
  1181. document.dispatchEvent(new MouseEvent('mouseup'));
  1182. return false;
  1183. }
  1184. }
  1185. }
  1186.  
  1187. function makeDraggable(div) {
  1188. div.draggable = true;
  1189. div.addEventListener('dragstart', function(e) {
  1190. var offsetY = e.offsetY || e.clientY - div.getBoundingClientRect().top;
  1191. if (offsetY > div.clientHeight - 30)
  1192. return e.preventDefault();
  1193.  
  1194. e.dataTransfer.setData('text/plain', '');
  1195.  
  1196. var dropZone = document.createElement('div');
  1197. var dropZoneHeight = 400 / div.FYTE.cache.videoWidth * div.FYTE.cache.videoHeight;
  1198. dropZone.className = 'instant-youtube-dragndrop-placeholder';
  1199.  
  1200. document.body.addEventListener('dragenter', dragHandler);
  1201. document.body.addEventListener('dragover', dragHandler);
  1202. document.body.addEventListener('dragend', dragHandler);
  1203. document.body.addEventListener('drop', dragHandler);
  1204. function dragHandler(e) {
  1205. e.stopImmediatePropagation();
  1206. e.stopPropagation();
  1207. e.preventDefault();
  1208. switch (e.type) {
  1209. case 'dragover':
  1210. var playing = div.hasAttribute('playing');
  1211. var stub = e.target.closest('.instant-youtube-container[stub]') === div.FYTE.stub && div.FYTE.stub;
  1212. var gizmo = playing && !stub
  1213. ? {left:0, top:0, right:innerWidth, bottom:innerHeight}
  1214. : (stub || div).getBoundingClientRect();
  1215. var x = e.clientX, y = e.clientY;
  1216. var cx = (gizmo.left + gizmo.right) / 2;
  1217. var cy = (gizmo.top + gizmo.bottom) / 2;
  1218. var stay = !!stub || y >= cy-200 && y <= cy+200 && x >= cx-200 && x <= cx+200;
  1219. overrideCSS(dropZone, {
  1220. top: y < cy || stay ? '0' : 'auto',
  1221. bottom: y > cy || stay ? '0' : 'auto',
  1222. left: x < cx || stay ? '0' : 'auto',
  1223. right: x > cx || stay ? '0' : 'auto',
  1224. width: playing && stay && stub ? stub.clientWidth+'px' : '400px',
  1225. height: playing && stay && stub ? stub.clientHeight+'px' : dropZoneHeight + 'px',
  1226. margin: playing && stay ? 'auto' : '0',
  1227. position: !playing && stay || stub ? 'absolute' : 'fixed',
  1228. 'background-color': stub ? 'rgba(0,0,255,0.5)' : stay ? 'rgba(255,255,0,0.4)' : 'rgba(0,255,0,0.2)',
  1229. });
  1230. adjustPinnedOffset(dropZone, div);
  1231. (stay && !playing || stub ? (stub || div) : document.body).appendChild(dropZone);
  1232. break;
  1233. case 'dragend':
  1234. case 'drop':
  1235. var corner = calcPinnedCorner(dropZone);
  1236. dropZone.remove();
  1237. dropZone = null;
  1238. document.body.removeEventListener('dragenter', dragHandler);
  1239. document.body.removeEventListener('dragover', dragHandler);
  1240. document.body.removeEventListener('dragend', dragHandler);
  1241. document.body.removeEventListener('drop', dragHandler);
  1242. if (e.type === 'dragend')
  1243. break;
  1244. if (div.hasAttribute('playing'))
  1245. (corner ? $(div, '[pin="' + corner + '"]') : div.FYTE.stub).click();
  1246. else
  1247. startPlaying(div, {pin: corner});
  1248. }
  1249. }
  1250. });
  1251. }
  1252.  
  1253. function adjustPinnedOffset(el, self, corner) {
  1254. var offset = 0;
  1255. $$('.instant-youtube-container[pinned] [pin="' + (corner || calcPinnedCorner(el)) + '"][active]').forEach(function(pin) {
  1256. var container = pin.closest('[pinned]');
  1257. if (container !== el && container !== self) {
  1258. var bounds = container.getBoundingClientRect();
  1259. offset = Math.max(offset, el.style.top === '0px' ? bounds.bottom : innerHeight - bounds.top);
  1260. }
  1261. });
  1262. if (offset)
  1263. el.style[el.style.top === '0px' ? 'top' : 'bottom'] = offset + 'px';
  1264. }
  1265.  
  1266. function calcPinnedCorner(el) {
  1267. var t = el.style.top !== 'auto';
  1268. var b = el.style.bottom !== 'auto';
  1269. var l = el.style.left !== 'auto';
  1270. var r = el.style.right !== 'auto';
  1271. return t && b && l && r ? '' : (t ? 'top' : 'bottom') + '-' + (l ? 'left' : 'right');
  1272. }
  1273.  
  1274. function constrainPinnedSize(div, width) {
  1275. var maxWidth = window.innerWidth - 100 |0;
  1276. var triedExceeding = (width|0) > maxWidth;
  1277. width = Math.max(200, Math.min(maxWidth, width|0));
  1278. return {
  1279. w: width,
  1280. h: width / div.FYTE.cache.videoWidth * div.FYTE.cache.videoHeight,
  1281. triedExceeding: triedExceeding,
  1282. };
  1283. }
  1284.  
  1285. function showOptions(e) {
  1286. var optionsButton = e.target;
  1287. translateHTML(optionsButton, 'afterend', '\
  1288. <div class="instant-youtube-options">\
  1289. <span>\
  1290. <label tl style="width: 100% !important;">Size:&nbsp;\
  1291. <select data-action="size-mode">\
  1292. <option tl value="Original">Original\
  1293. <option tl value="Fit to width">Fit to width\
  1294. <option>360p\
  1295. <option>480p\
  1296. <option>720p\
  1297. <option>1080p\
  1298. <option tl value="Custom">Custom...\
  1299. </select>\
  1300. </label>&nbsp;\
  1301. <label data-action="size-custom" ' + (resizeMode !== 'Custom' ? 'disabled' : '') + '>\
  1302. <input type="number" min="320" max="9999" tl-placeholder="width" data-action="width" step="1" value="' + (resizeWidth||'') + '">\
  1303. x\
  1304. <input type="number" min="240" max="9999" tl-placeholder="height" data-action="height" step="1" value="' + (resizeHeight||'') + '">\
  1305. </label>\
  1306. </span>\
  1307. <label tl="content,title" title="msgStoryboardTip">\
  1308. <input data-action="storyboard" type="checkbox" ' + (showStoryboard ? 'checked' : '') + '>\
  1309. msgStoryboard\
  1310. </label>\
  1311. <span>\
  1312. <label tl="content,title" title="msgDirectTip">\
  1313. <input data-action="direct" type="checkbox" ' + (playDirectly ? 'checked' : '') + '>\
  1314. msgDirect\
  1315. </label>\
  1316. &nbsp;\
  1317. <label tl="content,title" title="msgDirectTip">\
  1318. <input data-action="direct-shown" type="checkbox" ' + (playDirectlyShown ? 'checked' : '') + '>\
  1319. msgDirectShown\
  1320. </label>\
  1321. </span>\
  1322. <label tl="content,title" title="msgSafeTip">\
  1323. <input data-action="safe" type="checkbox" ' + (skipCustom ? 'checked' : '') + '>\
  1324. msgSafe\
  1325. </label>\
  1326. <table>\
  1327. <tr>\
  1328. <td><label tl="content,title" title="msgPinningTip">msgPinning</label></td>\
  1329. <td>\
  1330. <select data-action="pinnable">\
  1331. <option tl value="on">msgPinningOn\
  1332. <option tl value="hide">msgPinningHover\
  1333. <option tl value="off">msgPinningOff\
  1334. </select>\
  1335. </td>\
  1336. </tr>\
  1337. <tr tl="title" title="msgQualityTip">\
  1338. <td><label tl="content">msgQuality</td>\
  1339. <td>\
  1340. <select data-action="quality">\
  1341. <option value="auto" tl>msgQualityAuto\
  1342. <option value="tiny">144p\
  1343. <option value="small">240p\
  1344. <option value="medium">360p\
  1345. <option value="large">480p\
  1346. <option value="hd720">720p\
  1347. <option value="hd1080">1080p\
  1348. <option value="hd1440">1440p\
  1349. <option value="hd2160">2160p (4K)\
  1350. <option value="hd2880">2880p (5K)\
  1351. <option value="highres">4320p (8K)\
  1352. </select>\
  1353. </td>\
  1354. </tr>\
  1355. </table>\
  1356. <span data-action="buttons">\
  1357. <button tl data-action="ok">OK</button>\
  1358. <button tl data-action="cancel">Cancel</button>\
  1359. </span>\
  1360. </div>\
  1361. ');
  1362. var options = optionsButton.nextElementSibling;
  1363.  
  1364. options.addEventListener('keydown', function(e) {
  1365. if (e.target.localName === 'input' &&
  1366. !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && e.key.match(/[.,]/))
  1367. return false;
  1368. });
  1369.  
  1370. $(options, '[data-action="size-mode"]').value = resizeMode;
  1371. $(options, '[data-action="size-mode"]').addEventListener('change', function() {
  1372. var v = this.value !== 'Custom';
  1373. var e = $(options, '[data-action="size-custom"]');
  1374. e.children[0].disabled = e.children[1].disabled = v;
  1375. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  1376. });
  1377.  
  1378. $(options, '[data-action="pinnable"]').value = pinnable;
  1379.  
  1380. $(options, '[data-action="quality"]').value = playQuality;
  1381.  
  1382. $(options, '[data-action="buttons"]').addEventListener('click', function(e) {
  1383. if (e.target.dataset.action !== 'ok') {
  1384. options.remove();
  1385. return;
  1386. }
  1387. var v, shouldAdjust;
  1388. if (resizeMode !== (v = $(options, '[data-action="size-mode"]').value)) {
  1389. GM_setValue('resize', resizeMode = v);
  1390. shouldAdjust = true;
  1391. }
  1392. if (resizeMode === 'Custom') {
  1393. var w = $(options, '[data-action="width"]').value |0;
  1394. var h = $(options, '[data-action="height"]').value |0;
  1395. if (resizeWidth !== w || resizeHeight !== h) {
  1396. updateCustomSize(w, h);
  1397. GM_setValue('width', resizeWidth);
  1398. GM_setValue('height', resizeHeight);
  1399. shouldAdjust = true;
  1400. }
  1401. }
  1402. if (showStoryboard !== (v = $(options, '[data-action="storyboard"]').checked)) {
  1403. GM_setValue('showStoryboard', showStoryboard = v);
  1404. $$('.instant-youtube-container').forEach(updateHoverHandler);
  1405. }
  1406. if (playDirectly !== (v = $(options, '[data-action="direct"]').checked)) {
  1407. GM_setValue('playHTML5', playDirectly = v);
  1408. if (playDirectlyShown) {
  1409. var newAltText = _(playDirectly ? 'Play with Youtube player' : 'Play directly (up to 720p)');
  1410. $$('.instant-youtube-alternative').forEach(function(e) {
  1411. e.textContent = newAltText;
  1412. });
  1413. }
  1414. }
  1415. if (playDirectlyShown !== (v = $(options, '[data-action="direct-shown"]').checked)) {
  1416. GM_setValue('playHTML5', playDirectlyShown = v);
  1417. updateAltPlayerCSS();
  1418. }
  1419. if (skipCustom !== (v = $(options, '[data-action="safe"]').checked)) {
  1420. GM_setValue('skipCustom', skipCustom = v);
  1421. }
  1422. if (pinnable !== (v = $(options, '[data-action="pinnable"]').value)) {
  1423. GM_setValue('pinnable', pinnable = v);
  1424. }
  1425. if (playQuality !== (v = $(options, '[data-action="quality"]').value)) {
  1426. GM_setValue('quality', playQuality = v);
  1427. }
  1428.  
  1429. options.remove();
  1430.  
  1431. if (shouldAdjust)
  1432. adjustNodes(e, e.target.closest('.instant-youtube-container'));
  1433. });
  1434. }
  1435.  
  1436. function updateCustomSize(w, h) {
  1437. resizeWidth = Math.min(9999, Math.max(320, w|0 || resizeWidth|0));
  1438. resizeHeight = Math.min(9999, Math.max(240, h|0 || resizeHeight|0));
  1439. }
  1440.  
  1441. function updateAltPlayerCSS() {
  1442. var s = '.instant-youtube-alternative { display:' + (playDirectlyShown ? 'block' : 'none') + '!important}';
  1443. $('style#instant-youtube-styles').textContent += s;
  1444. return s;
  1445. }
  1446.  
  1447. function important(cssText) {
  1448. return cssText.replace(/;/g, '!important;');
  1449. }
  1450.  
  1451. function tryCatch(func) {
  1452. try {
  1453. return func();
  1454. } catch(e) {
  1455. console.log(e);
  1456. }
  1457. }
  1458.  
  1459. function getFunctionComment(fn) {
  1460. return fn.toString().match(/\/\*([\s\S]*?)\*\/\s*}$/)[1];
  1461. }
  1462.  
  1463. function $(selORnode, sel) {
  1464. return sel ? selORnode.querySelector(sel)
  1465. : document.querySelector(selORnode);
  1466. }
  1467.  
  1468. function $$(selORnode, sel) {
  1469. return Array.prototype.slice.call(
  1470. sel ? selORnode.querySelectorAll(sel)
  1471. : document.querySelectorAll(selORnode));
  1472. }
  1473.  
  1474. function $$remove(selORnode, sel) {
  1475. Array.prototype.forEach.call(
  1476. sel ? selORnode.querySelectorAll(sel)
  1477. : document.querySelectorAll(selORnode),
  1478. function(e) { e.remove() }
  1479. );
  1480. }
  1481.  
  1482. function overrideCSS(e, params) {
  1483. var names = Object.keys(params);
  1484. var style = e.style.cssText.replace(new RegExp('(^|\s|;)(' + names.join('|') + ')(:[^;]+)', 'gi'), '$1');
  1485. e.style.cssText = style.replace(/[^;]\s*$/, '$&;').replace(/^\s*;\s*/, '') +
  1486. names.map(function(n) { return n + ':' + params[n] + '!important' }).join(';') + ';';
  1487. }
  1488.  
  1489. // fix dumb Firefox bug
  1490. function floatPadding(node, style, dir) {
  1491. var padding = style['padding' + dir];
  1492. if (padding.indexOf('%') < 0)
  1493. return parseFloat(padding);
  1494. return parseFloat(padding) * (parseFloat(style.width) || node.clientWidth) / 100;
  1495. }
  1496.  
  1497. function cleanupCache() {
  1498. for (var k in localStorage) {
  1499. if (k.lastIndexOf('FYTE-cache-', 0) === 0
  1500. && Date.now() - Number((tryJSONparse(localStorage[k]) || {}).lastUsed || 0) > CACHE_STALE_DURATION) {
  1501. delete localStorage[k];
  1502. }
  1503. }
  1504. GM_listValues().forEach(function(k) {
  1505. if (k.lastIndexOf('cache-', 0) === 0) {
  1506. GM_deleteValue(k);
  1507. }
  1508. });
  1509. }
  1510.  
  1511. function tryJSONparse(s) {
  1512. try { return JSON.parse(s) }
  1513. catch (e) {}
  1514. }
  1515.  
  1516. function translateHTML(baseElement, place, html) {
  1517. var tmp = document.createElement('div');
  1518. tmp.innerHTML = html;
  1519. $$(tmp, '[tl]').forEach(function(node) {
  1520. (node.getAttribute('tl') || 'content').split(',').forEach(function(what) {
  1521. var child, src, tl;
  1522. if (what === 'content') {
  1523. for (var i = node.childNodes.length-1, n; (i>=0) && (n=node.childNodes[i]); i--) {
  1524. if (n.nodeType === Node.TEXT_NODE && n.textContent.trim()) {
  1525. child = n;
  1526. break;
  1527. }
  1528. }
  1529. } else
  1530. child = node.getAttributeNode(what);
  1531. if (!child)
  1532. return;
  1533. src = child.textContent;
  1534. var srcTrimmed = src.trim();
  1535. tl = src.replace(srcTrimmed, _(srcTrimmed));
  1536. if (src !== tl)
  1537. child.textContent = tl;
  1538. });
  1539. });
  1540. baseElement.insertAdjacentHTML(place, tmp.innerHTML);
  1541. }
  1542.  
  1543. function initTL() {
  1544. var tlSource = {
  1545. 'watch on Youtube': {
  1546. 'ru': 'открыть на Youtube',
  1547. },
  1548. 'Play with Youtube player': {
  1549. 'ru': 'Включить плеер Youtube',
  1550. },
  1551. 'Play directly (up to 720p)': {
  1552. 'ru': 'Включить напрямую (макс. 720p)',
  1553. },
  1554. msgAltPlayerHint: {
  1555. 'en': 'Shift-click to use alternative player',
  1556. 'ru': 'Shift-клик для смены типа плеера',
  1557. },
  1558. 'Options': {
  1559. 'ru': 'Опции',
  1560. },
  1561. 'Size:': {
  1562. 'ru': 'Размер:',
  1563. },
  1564. 'Original': {
  1565. 'ru': 'Исходный',
  1566. },
  1567. 'Fit to width': {
  1568. 'ru': 'На всю ширину',
  1569. },
  1570. 'Custom...': {
  1571. 'ru': 'Настроить...',
  1572. },
  1573. 'width': {
  1574. 'ru': 'ширина',
  1575. },
  1576. 'height': {
  1577. 'ru': 'высота',
  1578. },
  1579. msgStoryboard: {
  1580. 'en': 'Storyboard thumbnails on hover',
  1581. 'ru': 'Раскадровка при наведении курсора',
  1582. },
  1583. msgStoryboardTip: {
  1584. 'en': 'Show storyboard preview on mouse hover at the bottom',
  1585. 'ru': 'Показывать миникадры при наведении мыши на низ кавер-картинки',
  1586. },
  1587. msgDirect: {
  1588. 'en': 'Play directly',
  1589. 'ru': 'Встроенный плеер браузера',
  1590. },
  1591. msgDirectTip: {
  1592. 'en': 'Note: Shift-click a thumbnail to use alternative player',
  1593. 'ru': 'Напоминание: удерживайте клавишу Shift при щелчке на картинке для альтернативного плеера',
  1594. },
  1595. msgDirectShown: {
  1596. 'en': 'Show under play button',
  1597. 'ru': 'Показывать под кнопкой ►',
  1598. },
  1599. msgSafe: {
  1600. 'en': 'Safe (skip videos with enablejsapi=1)',
  1601. 'ru': 'Консервативный режим',
  1602. },
  1603. msgSafeTip: {
  1604. 'en': 'Do not process customized videos with enablejsapi=1 parameter (requires page reload)',
  1605. 'ru': 'Не обрабатывать нестандартные видео с параметром enablejsapi=1 (подействует после обновления страницы)',
  1606. },
  1607. msgPinning: {
  1608. 'en': 'Corner pinning',
  1609. 'ru': 'Закрепление по углам',
  1610. },
  1611. msgPinningTip: {
  1612. 'en': 'Enable corner pinning controls when a video is playing. \nTo restore the video click the active corner pin or the original video placeholder.',
  1613. 'ru': 'Включить шпильки по углам для закрепления видео во время просмотра. \nДля отмены можно нажать еще раз на активированный уголЪ или на заглушку, где исходно было видео',
  1614. },
  1615. msgPinningOn: {
  1616. 'en': 'On',
  1617. 'ru': 'Да',
  1618. },
  1619. msgPinningHover: {
  1620. 'en': 'On, hover a corner to show',
  1621. 'ru': 'Да, при наведении курсора',
  1622. },
  1623. msgPinningOff: {
  1624. 'en': 'Off',
  1625. 'ru': 'Нет',
  1626. },
  1627. msgQuality: {
  1628. 'en': 'Youtube quality',
  1629. 'ru': 'Качество youtube',
  1630. },
  1631. msgQualityTip: {
  1632. 'en': 'Youtube player video quality',
  1633. 'ru': 'Качество видео в youtube-плеере',
  1634. },
  1635. msgQualityAuto: {
  1636. 'en': 'auto',
  1637. 'ru': 'не выбрано',
  1638. },
  1639. 'OK': {
  1640. 'ru': 'ОК',
  1641. },
  1642. 'Cancel': {
  1643. 'ru': 'Оменить',
  1644. },
  1645. };
  1646. var browserLang = navigator.language || navigator.languages && navigator.languages[0] || '';
  1647. var browserLangMajor = browserLang.replace(/-.+/, '');
  1648. var tl = {};
  1649. Object.keys(tlSource).forEach(function(k) {
  1650. var langs = tlSource[k];
  1651. var text = langs[browserLang] || langs[browserLangMajor];
  1652. if (text)
  1653. tl[k] = text;
  1654. });
  1655. return function(src) { return tl[src] || src };
  1656. }
  1657.  
  1658. function injectStylesIfNeeded(force) {
  1659. if (!fytedom[0] && !force)
  1660. return;
  1661. var styledom = $('style#instant-youtube-styles');
  1662. if (styledom) {
  1663. // move our rules to the end of HEAD to increase CSS specificity
  1664. if (styledom.nextElementSibling && document.head)
  1665. document.head.insertBefore(styledom, null);
  1666. return;
  1667. }
  1668. styledom = (document.head || document.documentElement).appendChild(document.createElement('style'));
  1669. styledom.id = 'instant-youtube-styles';
  1670. styledom.textContent = important(getFunctionComment(function() { /*
  1671. .instant-youtube-container,
  1672. .instant-youtube-wrapper * {
  1673. transform: translate3D(0,0,0);
  1674. }
  1675. .instant-youtube-container {
  1676. all: unset;
  1677. contain: strict;
  1678. display: block;
  1679. position: relative;
  1680. overflow: hidden;
  1681. cursor: pointer;
  1682. padding: 0;
  1683. margin: auto;
  1684. font: normal 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1685. text-align: center;
  1686. background: black;
  1687. break-inside: avoid-column;
  1688. }
  1689. .instant-youtube-container[disabled] {
  1690. background: #888;
  1691. }
  1692. .instant-youtube-container[disabled] .instant-youtube-storyboard {
  1693. display: none;
  1694. }
  1695. .instant-youtube-container[pinned] {
  1696. box-shadow: 0 0 30px black;
  1697. }
  1698. .instant-youtube-container[playing] {
  1699. contain: none;
  1700. }
  1701. .instant-youtube-wrapper {
  1702. width: 100%;
  1703. height: 100%;
  1704. }
  1705. .instant-youtube-play-button {
  1706. display: block;
  1707. position: absolute;
  1708. width: 85px;
  1709. height: 60px;
  1710. left: 0;
  1711. right: 0;
  1712. top: 0;
  1713. bottom: 0;
  1714. margin: auto;
  1715. }
  1716. .instant-youtube-loading-spinner {
  1717. display: block;
  1718. position: absolute;
  1719. width: 20px;
  1720. height: 20px;
  1721. left: 0;
  1722. right: 0;
  1723. top: 0;
  1724. bottom: 0;
  1725. padding: 0;
  1726. margin: auto;
  1727. pointer-events: none;
  1728. background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==");
  1729. }
  1730. .instant-youtube-container:hover .ytp-large-play-button-svg {
  1731. fill: #CC181E;
  1732. }
  1733. .instant-youtube-alternative {
  1734. display: block;
  1735. position: absolute;
  1736. width: 20em;
  1737. height: 20px;
  1738. top: 50%;
  1739. left: 0;
  1740. right: 0;
  1741. margin: 60px auto;
  1742. padding: 0;
  1743. border: none;
  1744. text-align: center;
  1745. text-decoration: none;
  1746. text-shadow: 1px 1px 3px black;
  1747. font-weight: bold;
  1748. color: white;
  1749. z-index: 8;
  1750. font-weight: normal;
  1751. font-size: 12px;
  1752. }
  1753. .instant-youtube-alternative:hover {
  1754. text-decoration: underline;
  1755. color: white;
  1756. background: transparent;
  1757. }
  1758. .instant-youtube-embed {
  1759. z-index: 10;
  1760. background: transparent;
  1761. }
  1762. .instant-youtube-title {
  1763. z-index: 20;
  1764. display: block;
  1765. position: absolute;
  1766. width: auto;
  1767. top: 0;
  1768. left: 0;
  1769. right: 0;
  1770. margin: 0;
  1771. padding: 7px;
  1772. border: none;
  1773. text-shadow: 1px 1px 2px black;
  1774. text-align: center;
  1775. text-decoration: none;
  1776. color: white;
  1777. background-color: rgba(0, 0, 0, 0.5);
  1778. }
  1779. .instant-youtube-title strong {
  1780. font: bold 14px/1.0 sans-serif, Arial, Helvetica, Verdana;
  1781. }
  1782. .instant-youtube-title strong:after {
  1783. content: " - $tl:'watch on Youtube'";
  1784. font-weight: normal;
  1785. margin-right: 1ex;
  1786. }
  1787. .instant-youtube-title span {
  1788. color: white;
  1789. }
  1790. .instant-youtube-title span:before {
  1791. content: "(";
  1792. }
  1793. .instant-youtube-title span:after {
  1794. content: ")";
  1795. }
  1796. .instant-youtube-container .instant-youtube-title i {
  1797. all: unset;
  1798. opacity: .5;
  1799. font-style: normal;
  1800. color: white;
  1801. }
  1802. @-webkit-keyframes instant-youtube-fadein {
  1803. from { opacity: 0 }
  1804. to { opacity: 1 }
  1805. }
  1806. @-moz-keyframes instant-youtube-fadein {
  1807. from { opacity: 0 }
  1808. to { opacity: 1 }
  1809. }
  1810. @keyframes instant-youtube-fadein {
  1811. from { opacity: 0 }
  1812. to { opacity: 1 }
  1813. }
  1814. .instant-youtube-container:not(:hover) .instant-youtube-title[hidden] {
  1815. display: none;
  1816. margin: 0;
  1817. }
  1818. .instant-youtube-title:hover {
  1819. text-decoration: underline;
  1820. }
  1821. .instant-youtube-title strong {
  1822. color: white;
  1823. }
  1824. .instant-youtube-options-button {
  1825. opacity: 0.6;
  1826. position: absolute;
  1827. right: 0;
  1828. bottom: 0;
  1829. margin: 0;
  1830. padding: 1.5ex 2ex;
  1831. font-size: 11px;
  1832. text-shadow: 1px 1px 2px black;
  1833. color: white;
  1834. }
  1835. .instant-youtube-options-button:hover {
  1836. opacity: 1;
  1837. background: rgba(0, 0, 0, 0.5);
  1838. }
  1839. .instant-youtube-options {
  1840. display: flex;
  1841. position: absolute;
  1842. right: 0;
  1843. bottom: 0;
  1844. margin: 0;
  1845. padding: 1ex 1ex 2ex 2ex;
  1846. flex-direction: column;
  1847. align-items: flex-start;
  1848. line-height: 1.5;
  1849. text-align: left;
  1850. opacity: 1;
  1851. color: white;
  1852. background: black;
  1853. z-index: 999;
  1854. }
  1855. .instant-youtube-options * {
  1856. width: auto;
  1857. height: auto;
  1858. margin: 0;
  1859. padding: 0;
  1860. font: inherit;
  1861. font-size: 13px;
  1862. vertical-align: middle;
  1863. text-transform: none;
  1864. text-align: left;
  1865. border-radius: 0;
  1866. text-decoration: none;
  1867. color: white;
  1868. background: black;
  1869. }
  1870. .instant-youtube-options > * {
  1871. margin-top: 1ex;
  1872. }
  1873. .instant-youtube-options table {
  1874. all: unset;
  1875. display: table;
  1876. }
  1877. .instant-youtube-options tr {
  1878. all: unset;
  1879. display: table-row;
  1880. }
  1881. .instant-youtube-options td {
  1882. all: unset;
  1883. display: table-cell;
  1884. padding: 2px;
  1885. }
  1886. .instant-youtube-options label > * {
  1887. display: inline;
  1888. }
  1889. .instant-youtube-options select {
  1890. padding: .5ex .25ex;
  1891. border: 1px solid #444;
  1892. -webkit-appearance: menulist;
  1893. }
  1894. .instant-youtube-options [data-action="size-custom"] input {
  1895. width: 9ex;
  1896. padding: .5ex .5ex .4ex;
  1897. border: 1px solid #666;
  1898. }
  1899. .instant-youtube-options [data-action="buttons"] {
  1900. margin-top: 1em;
  1901. }
  1902. .instant-youtube-options button {
  1903. margin: 0 1ex 0 0;
  1904. padding: .5ex 2ex;
  1905. border: 2px solid gray;
  1906. font-weight: bold;
  1907. }
  1908. .instant-youtube-options button:hover {
  1909. border-color: white;
  1910. }
  1911. .instant-youtube-options label[disabled] {
  1912. opacity: 0.25;
  1913. }
  1914. .instant-youtube-storyboard {
  1915. height: 33%;
  1916. max-height: 90px;
  1917. display: block;
  1918. position: absolute;
  1919. left: 0;
  1920. right: 0;
  1921. bottom: 0;
  1922. overflow: visible;
  1923. overflow-x: visible;
  1924. overflow-y: visible;
  1925. }
  1926. .instant-youtube-storyboard:hover {
  1927. background-color: rgba(0,0,0,0.3);
  1928. }
  1929. .instant-youtube-storyboard[disabled] {
  1930. display:none;
  1931. }
  1932. .instant-youtube-storyboard div {
  1933. display: block;
  1934. position: absolute;
  1935. bottom: 0px;
  1936. pointer-events: none;
  1937. border: 3px solid #888;
  1938. box-shadow: 2px 2px 10px black;
  1939. transition: opacity .25s ease;
  1940. background-color: transparent;
  1941. background-origin: content-box;
  1942. opacity: 0;
  1943. }
  1944. .instant-youtube-storyboard:hover div {
  1945. opacity: 1;
  1946. }
  1947. .instant-youtube-container [pin] {
  1948. position: absolute;
  1949. width: 0;
  1950. height: 0;
  1951. margin: 0;
  1952. padding: 0;
  1953. top: auto; bottom: auto; left: auto; right: auto;
  1954. border-style: solid;
  1955. transition: opacity 2.5s ease-in, opacity 0.4s ease-out;
  1956. opacity: 0;
  1957. z-index: 100;
  1958. }
  1959. .instant-youtube-container[playing]:hover [pin]:not([transparent]) {
  1960. opacity: 1;
  1961. }
  1962. .instant-youtube-container[playing] [pin]:hover {
  1963. cursor: alias;
  1964. opacity: 1;
  1965. transition: opacity 0s;
  1966. }
  1967. .instant-youtube-container [pin=top-left][active] { border-top-color: green; }
  1968. .instant-youtube-container [pin=top-left]:hover { border-top-color: #fc0; }
  1969. .instant-youtube-container [pin=top-left] {
  1970. top: 0; left: 0;
  1971. border-width: 10px 10px 0 0;
  1972. border-color: red transparent transparent transparent;
  1973. }
  1974. .instant-youtube-container [pin=top-left][transparent] {
  1975. border-width: 10px 10px 0 0;
  1976. }
  1977. .instant-youtube-container [pin=top-right][active] { border-right-color: green; }
  1978. .instant-youtube-container [pin=top-right]:hover { border-right-color: #fc0; }
  1979. .instant-youtube-container [pin=top-right] {
  1980. top: 0; right: 0;
  1981. border-width: 0 10px 10px 0;
  1982. border-color: transparent red transparent transparent;
  1983. }
  1984. .instant-youtube-container [pin=top-right][transparent] {
  1985. border-width: 0 10px 10px 0;
  1986. }
  1987. .instant-youtube-container [pin=bottom-right][active] { border-bottom-color: green; }
  1988. .instant-youtube-container [pin=bottom-right]:hover { border-bottom-color: #fc0; }
  1989. .instant-youtube-container [pin=bottom-right] {
  1990. bottom: 0; right: 0;
  1991. border-width: 0 0 10px 10px;
  1992. border-color: transparent transparent red transparent;
  1993. }
  1994. .instant-youtube-container [pin=bottom-right][transparent] {
  1995. border-width: 0 0 10px 10px;
  1996. }
  1997. .instant-youtube-container [pin=bottom-left][active] { border-left-color: green; }
  1998. .instant-youtube-container [pin=bottom-left]:hover { border-left-color: #fc0; }
  1999. .instant-youtube-container [pin=bottom-left] {
  2000. bottom: 0; left: 0;
  2001. border-width: 10px 0 0 10px;
  2002. border-color: transparent transparent transparent red;
  2003. }
  2004. .instant-youtube-container [pin=bottom-left][transparent] {
  2005. border-width: 10px 0 0 10px;
  2006. }
  2007. .instant-youtube-dragndrop-placeholder {
  2008. z-index: 999999999;
  2009. margin: 0;
  2010. padding: 0;
  2011. background: rgba(0, 255, 0, 0.1);
  2012. border: 2px dotted green;
  2013. box-sizing: border-box;
  2014. pointer-events: none;
  2015. }
  2016. .instant-youtube-container [size-gripper] {
  2017. width: 0;
  2018. position: absolute;
  2019. top: 0;
  2020. bottom: 0;
  2021. cursor: e-resize;
  2022. border-color: rgba(50,100,255,0.5);
  2023. border-width: 12px;
  2024. background: rgba(50,100,255,0.2);
  2025. z-index: 99;
  2026. opacity: 0;
  2027. transition: opacity .1s ease-in-out, border-color .1s ease-in-out;
  2028. }
  2029. .instant-youtube-container[pinned*="right"] [size-gripper] {
  2030. border-style: none none none solid;
  2031. left: -4px;
  2032. }
  2033. .instant-youtube-container[pinned*="left"] [size-gripper] {
  2034. border-style: none solid none none;
  2035. right: -4px;
  2036. }
  2037. .instant-youtube-container [size-gripper]:hover {
  2038. opacity: 1;
  2039. }
  2040. .instant-youtube-container [size-gripper]:active {
  2041. opacity: 1;
  2042. width: auto;
  2043. left: -4px;
  2044. right: -4px;
  2045. }
  2046. .instant-youtube-container [size-gripper][tried-exceeding] {
  2047. border-color: rgba(255,0,0,0.5);
  2048. }
  2049. .instant-youtube-container [size-gripper][saveAs="global"] {
  2050. border-color: rgba(0,255,0,0.5);
  2051. }
  2052. .instant-youtube-container [size-gripper][saveAs="site"] {
  2053. border-color: rgba(0,255,255,0.5);
  2054. }
  2055. .instant-youtube-container [size-gripper][saveAs="reset"] {
  2056. border-color: rgba(255,255,0,0.5);
  2057. }
  2058. .instant-youtube-container [size-gripper][saveAs="cancel"] {
  2059. border-color: rgba(255,0,255,0.25);
  2060. }
  2061. .instant-youtube-container [size-gripper] > div {
  2062. white-space: nowrap;
  2063. color: white;
  2064. font-weight: normal;
  2065. line-height: 1.25;
  2066. text-align: left;
  2067. position: absolute;
  2068. top: 50%;
  2069. padding: 1ex 1em 1ex;
  2070. background-color: rgba(80,150,255,0.5);
  2071. }
  2072. .instant-youtube-container [size-gripper] [save-as="site"] {
  2073. font-weight: bold;
  2074. color: yellow;
  2075. }
  2076. .instant-youtube-container[pinned*="left"] [size-gripper] > div {
  2077. right: 0;
  2078. }
  2079. */}).replace(/\$tl:'(.+?)'/g, function(m, m1) { return _(m1) })
  2080. ) +
  2081. updateAltPlayerCSS();
  2082. }

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址