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.

当前为 2020-02-21 提交的版本,查看 最新版本

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