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.

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

QingJ © 2025

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