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