FYTE /Fast YouTube Embedded/ Player

Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background. HTML5 direct playback (720p max) is used when selected and available.

当前为 2016-07-15 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name FYTE /Fast YouTube Embedded/ Player
  3. // @description Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background. HTML5 direct playback (720p max) is used when selected and available.
  4. // @version 2.1.3
  5. // @include *
  6. // @exclude https://www.youtube.com/*
  7. // @author wOxxOm
  8. // @namespace wOxxOm.scripts
  9. // @license MIT License
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @grant GM_addStyle
  13. // @grant GM_xmlhttpRequest
  14. // @connect www.youtube.com
  15. // @connect youtube.com
  16. // @run-at document-start
  17. // @require https://gf.qytechs.cn/scripts/12228/code/setMutationHandler.js
  18. // ==/UserScript==
  19.  
  20. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  21.  
  22. var resizeMode = GM_getValue('resize', 'Fit to width');
  23. if (typeof resizeMode != 'string')
  24. resizeMode = resizeMode ? 'Fit to width' : 'Original';
  25.  
  26. var resizeWidth = GM_getValue('width', 1280) |0;
  27. var resizeHeight = GM_getValue('height', 720) |0;
  28. updateCustomSize();
  29.  
  30. var playHTML5 = !!GM_getValue('playHTML5', false);
  31. var skipCustom = !!GM_getValue('skipCustom', true);
  32. var showStoryboard = !!GM_getValue('showStoryboard', true);
  33.  
  34. var $ = function(selORnode, sel) { return sel ? selORnode.querySelector(sel) : document.querySelector(selORnode) };
  35. var $$ = function(selORnode, sel) { return Array.prototype.slice.call(sel ? selORnode.querySelectorAll(sel) : document.querySelectorAll(selORnode)) };
  36.  
  37. var embedSelector = 'iframe[src*="youtube.com/embed"], embed[src*="youtube.com/v"]';
  38.  
  39. document.addEventListener('DOMContentLoaded', function(e) {
  40. adjustNodesIfNeeded(e);
  41. injectStylesIfNeeded();
  42. });
  43.  
  44. window.addEventListener('resize', adjustNodesIfNeeded);
  45.  
  46. processEmbeds($$(embedSelector));
  47. setMutationHandler(document, embedSelector, processEmbeds);
  48.  
  49. function processEmbeds(nodes) {
  50. for (var i=0, nl=nodes.length, n; i<nl && (n=nodes[i]); i++) {
  51. var np = n.parentNode, npw;
  52. if (!np ||
  53. skipCustom && n.src.indexOf('enablejsapi=1') > 0 ||
  54. np.localName == 'object' && !np.parentNode ||
  55. n.className.indexOf('instant-youtube-') >= 0 ||
  56. n.src.indexOf('autoplay=1') > 0 ||
  57. n.onload && getComputedStyle(np).display == 'none' // skip some retarded loaders
  58. )
  59. continue;
  60.  
  61. var id = n.src.match(/(?:embed\/|v[=\/])([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
  62. if (!id)
  63. continue;
  64. id = id[1];
  65.  
  66. var div = document.createElement('div');
  67. div.className = 'instant-youtube-container';
  68. div.FYTE = {
  69. state: 'querying',
  70. srcEmbed: n.src.replace(/&$/, ''),
  71. videoID: id,
  72. originalWidth: n.width|0 || n.clientWidth,
  73. originalHeight: n.height|0 || n.clientHeight,
  74. };
  75.  
  76. var divSize = calcThumbSize(div, n);
  77. div.style.maxWidth = divSize.w + 'px';
  78. div.style.height = divSize.h + 'px';
  79.  
  80. var wrapper = div.appendChild(document.createElement('div'));
  81. wrapper.className = 'instant-youtube-wrapper';
  82.  
  83. var img = wrapper.appendChild(document.createElement('img'));
  84. img.className = 'instant-youtube-thumbnail';
  85. img.src = 'https://i.ytimg.com/vi/' + id + '/maxresdefault.jpg';
  86. img.style.cssText = important('transition:opacity 0.1s ease-out; opacity:0; padding:0; margin:auto; position:absolute; left:0; right:0; top:0; bottom:0;');
  87.  
  88. img.title = 'Shift-click to use alternative player';
  89. img.onload = function(e) {
  90. var img = e.target;
  91. if (img.naturalWidth <= 120)
  92. return img.onerror(e);
  93. var fitToWidth = true;
  94. if (img.naturalHeight) {
  95. var ratio = img.naturalWidth / img.naturalHeight;
  96. if (ratio > 4.1/3 && ratio < divSize.w/divSize.h) {
  97. img.style.cssText += important('width:auto; height:100%;');
  98. fitToWidth = false;
  99. }
  100. }
  101. if (fitToWidth) {
  102. img.style.cssText += important('width:100%; height:auto;');
  103. }
  104. if (img.videoWidth)
  105. fixThumbnailAR(div);
  106. img.style.opacity = 1;
  107. };
  108. img.onerror = function(e) {
  109. var img = e.target;
  110. if (img.src.indexOf('maxresdefault') > 0)
  111. img.src = img.src.replace('maxresdefault','hqdefault');
  112. };
  113.  
  114. GM_xmlhttpRequest({
  115. method: 'GET',
  116. url: 'https://www.youtube.com/get_video_info?video_id=' + div.FYTE.videoID + '&el=detailpage',
  117. headers: {'Accept-Encoding': 'gzip'},
  118. context: div,
  119. onload: parseVideoInfo
  120. });
  121.  
  122. wrapper.insertAdjacentHTML('beforeend', '\
  123. <a class="instant-youtube-title" target="_blank" href="' +
  124. div.FYTE.srcEmbed.replace(/^http:/, 'https:').replace('?', '&').replace(/\/embed\//, '/watch?v=').replace(/&?wmode=\w+/, '') +
  125. '">&nbsp;</a>\
  126. <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>\
  127. <span class="instant-youtube-link">' + (playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  128. <div class="instant-youtube-storyboard"></div>\
  129. <div class="instant-youtube-options-button">Options</div>\
  130. ');
  131.  
  132. if (n.parentNode.localName == 'object')
  133. n = n.parentNode;
  134. n.parentNode.insertBefore(div, n);
  135. n.remove();
  136.  
  137. div.addEventListener('click', clickHandler);
  138. attachHoverHandlerIfNeeded(div);
  139. }
  140.  
  141. injectStylesIfNeeded();
  142. return true;
  143. }
  144.  
  145. function attachHoverHandlerIfNeeded(div) {
  146. if (!showStoryboard)
  147. return;
  148. div.addEventListener('mouseover', function hoverHandler(e) {
  149. if (!showStoryboard)
  150. return;
  151. div.removeEventListener('mouseover', hoverHandler);
  152. $(div, '.instant-youtube-storyboard').innerHTML = '123'
  153. .replace(/./g, '<div><img src="https://i.ytimg.com/vi/' + div.FYTE.videoID + '/$&.jpg"></div>');
  154. });
  155. }
  156.  
  157. function adjustNodesIfNeeded(e) {
  158. if (resizeMode != 'Original' && !adjustNodesIfNeeded.scheduled)
  159. adjustNodesIfNeeded.scheduled = setTimeout(function() {
  160. adjustNodes(e);
  161. adjustNodesIfNeeded.scheduled = 0;
  162. }, 16);
  163. }
  164.  
  165. function adjustNodes(e, clickedContainer) {
  166. var force = !!clickedContainer;
  167. var nearest = force ? clickedContainer : null;
  168.  
  169. var vids = $$('div.instant-youtube-container');
  170.  
  171. if (!nearest && e.type != 'DOMContentLoaded') {
  172. var minDistance = window.innerHeight*3/4 |0;
  173. var nearTargetY = window.innerHeight/2;
  174. vids.forEach(function(n) {
  175. var bounds = n.getBoundingClientRect();
  176. var distance = Math.abs((bounds.bottom + bounds.top)/2 - nearTargetY);
  177. if (distance < minDistance) {
  178. minDistance = distance;
  179. nearest = n;
  180. }
  181. });
  182. }
  183.  
  184. if (nearest) {
  185. var bounds = nearest.getBoundingClientRect();
  186. var nearestCenterYpct = (bounds.top + bounds.bottom)/2 / window.innerHeight;
  187. }
  188.  
  189. var resized = false;
  190.  
  191. vids.forEach(function(n) {
  192. var size = calcThumbSize(n);
  193. var w = size.w, h = size.h;
  194.  
  195. if (force && Math.abs(w - parseFloat(n.style.maxWidth)) <= 2)
  196. return;
  197.  
  198. if (n.style.maxWidth != w + 'px') n.style.maxWidth = w + 'px';
  199. if (n.style.height != h + 'px') n.style.height = h + 'px';
  200.  
  201. var video = $(n, 'video');
  202. if (video) {
  203. video.width = w;
  204. video.height = h;
  205. }
  206.  
  207. fixThumbnailAR(n);
  208. resized = true;
  209. });
  210.  
  211. if (resized && nearest)
  212. setTimeout(function() {
  213. var bounds = nearest.getBoundingClientRect();
  214. var h = bounds.bottom - bounds.top;
  215. var projectedCenterY = nearestCenterYpct * window.innerHeight;
  216. var projectedTop = projectedCenterY - h/2;
  217. var safeTop = Math.min(Math.max(0, projectedTop), window.innerHeight - h);
  218. window.scrollBy(0, bounds.top - safeTop);
  219. }, 16);
  220. }
  221.  
  222. function calcThumbSize(div, origNode) {
  223. var w, h;
  224. switch (resizeMode) {
  225. case 'Original':
  226. w = div.FYTE.originalWidth;
  227. h = div.FYTE.originalHeight;
  228. break;
  229. case 'Custom':
  230. w = resizeWidth;
  231. h = resizeHeight;
  232. break;
  233. case '1080p':
  234. case '720p':
  235. case '480p':
  236. case '360p':
  237. h = parseInt(resizeMode);
  238. w = Math.round(h / 9 * 16 + 0.49);
  239. break;
  240. default: // fit-to-width mode
  241. var n = origNode = origNode || div;
  242. do {
  243. n = n.parentElement;
  244. // find parent node with nonzero width (i.e. independent of our video element)
  245. } while (n && !(w = n.clientWidth));
  246. if (w)
  247. h = Math.round(w / 16 * 9 + 0.49);
  248. else {
  249. w = origNode.clientWidth;
  250. h = origNode.clientHeight;
  251. }
  252. }
  253. return {w:w, h:h};
  254. }
  255.  
  256. function parseVideoInfo(response) {
  257. var div = response.context;
  258. var txt = response.responseText;
  259. var info = tryCatch(function() { return JSON.parse(txt.replace(/(\w+)=?(.*?)(&|$)/g, '"$1":"$2",').replace(/^(.+?),?$/, '{$1}')) });
  260. var videoSources = [];
  261.  
  262. // parse width & height to adjust the thumbnail
  263. var m = decodeURIComponent(txt).match(/\b(\d+)x(\d+)\b/);
  264. if (m)
  265. fixThumbnailAR(div, m[1]|0, m[2]|0);
  266.  
  267. // parse video sources
  268. if (info.url_encoded_fmt_stream_map && info.fmt_list) {
  269. var streams = {};
  270. decodeURIComponent(info.url_encoded_fmt_stream_map).split(',').forEach(function(stream) {
  271. var params = {};
  272. stream.split('&').forEach(function(kv) {
  273. params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
  274. });
  275. streams[params.itag] = params;
  276. });
  277. decodeURIComponent(info.fmt_list).split(',').forEach(function(fmt) {
  278. var itag = fmt.split('/')[0];
  279. var dimensions = fmt.split('/')[1];
  280. var stream = streams[itag];
  281. if (stream) {
  282. videoSources.push({
  283. src: stream.url,
  284. title: stream.quality + ', ' + dimensions + ', ' + stream.type
  285. });
  286. }
  287. });
  288. } else {
  289. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  290. var text = decodeURIComponent(txt).split('url_encoded_fmt_stream_map')[1];
  291. while (m = rx.exec(text)) {
  292. videoSources.push({
  293. src: decodeURIComponent(decodeURIComponent(m[1]))
  294. });
  295. }
  296. }
  297.  
  298. var title = decodeURIComponent(info.title || '').replace(/\+/g, ' ');
  299. var duration = info.length_seconds|0 || '';
  300. if (duration) {
  301. var d = new Date(null);
  302. d.setSeconds(duration);
  303. duration = d.toISOString().replace(/^.+?T[0:]{0,4}(.+?)\..+$/, '<span>$1</span>');
  304. }
  305. if (title || duration) {
  306. $(div, '.instant-youtube-title').innerHTML = (title ? '<strong>' + title + '</strong>' : '') + duration;
  307. }
  308.  
  309. if (videoSources.length)
  310. div.FYTE.videoSources = videoSources;
  311.  
  312. injectStylesIfNeeded();
  313.  
  314. if (div.FYTE.state == 'scheduled play')
  315. setTimeout(function() { playDirectly(div) }, 0);
  316.  
  317. div.FYTE.state = '';
  318. }
  319.  
  320. function fixThumbnailAR(div, w, h) {
  321. var img = $(div, 'img');
  322. var thw = img.naturalWidth, thh = img.naturalHeight;
  323. if (!thw || !thh) {
  324. // thumbnail is still loading
  325. img.videoWidth = w;
  326. img.videoHeight = h;
  327. return;
  328. } else if (!w || !h) {
  329. w = img.videoWidth;
  330. h = img.videoHeight;
  331. }
  332. var divw = div.clientWidth, divh = div.clientHeight;
  333. // if both video and thumbnail are 4:3, fit the image to height
  334. if (Math.abs(h/w*divw / divh - 1) > 0.05 && Math.abs(thh/thw*divw / divh - 1) > 0.05) {
  335. img.style.cssText = img.style.cssText.replace(/\bheight:.*?;/, 'height:' + img.clientHeight + 'px!important;');
  336. if (!img.videoWidth) // skip animation if thumbnail is already loaded
  337. img.style.transition = 'height 1s ease, margin-top 1s ease';
  338. setTimeout(function() {
  339. img.style.cssText += important(h/w >= divh/divw ? 'width:auto; height:100%;' : 'width:100%; height:auto;');
  340. setTimeout(function() {
  341. img.style.transition = '';
  342. }, 1000);
  343. }, 0);
  344. }
  345. }
  346.  
  347. function clickHandler(e) {
  348. if (e.target.href)
  349. return;
  350. if (e.target.matches('.instant-youtube-options-button'))
  351. return showOptions(e);
  352. if (e.target.matches('.instant-youtube-options, .instant-youtube-options *'))
  353. return;
  354. div = e.target.closest('.instant-youtube-container');
  355. div.removeEventListener('click', clickHandler);
  356. $(div, 'svg').outerHTML = '<span class="instant-youtube-loading-button"></span>';
  357.  
  358. var alternateMode = e.shiftKey || e.target.className == 'instant-youtube-link';
  359. if ((!!playHTML5 + !!alternateMode == 1) && (div.FYTE.videoSources || div.FYTE.state == 'querying')) {
  360. if (div.FYTE.videoSources)
  361. playDirectly(div);
  362. else {
  363. // playback will start in parseVideoInfo
  364. div.FYTE.state = 'scheduled play';
  365. // fallback to iframe in 5s
  366. setTimeout(function() {
  367. if (div.FYTE.state) {
  368. div.FYTE.state = '';
  369. switchToIFrame.call(div);
  370. }
  371. }, 5000);
  372. }
  373. }
  374. else
  375. switchToIFrame.call(div);
  376. }
  377.  
  378. function playDirectly(div) {
  379. $(div, '.instant-youtube-options-button').style.display = 'none';
  380. $(div, '.instant-youtube-link').style.display = 'none';
  381.  
  382. var video = document.createElement('video');
  383. video.controls = true;
  384. video.autoplay = true;
  385. video.style.cssText = important(
  386. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:0; transition:opacity 2s;' +
  387. 'width:'+div.clientWidth+'px; height:'+div.clientHeight+'px;');
  388. video.className = 'instant-youtube-embed';
  389. video.volume = GM_getValue('volume', 0.5);
  390.  
  391. div.FYTE.videoSources.forEach(function(src) {
  392. var srcdom = video.appendChild(document.createElement('source'));
  393. Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
  394. srcdom.onerror = switchToIFrame.bind(div);
  395. });
  396.  
  397.  
  398. if (window.chrome) {
  399. video.addEventListener('click', function(e) {
  400. this.paused ? this.play() : this.pause();
  401. });
  402. }
  403. video.interval = (function() {
  404. return setInterval(function() {
  405. if (video.volume != GM_getValue('volume', 0.5))
  406. GM_setValue('volume', video.volume);
  407. }, 1000);
  408. })();
  409. var title = $(div, '.instant-youtube-title');
  410. if (title) {
  411. video.onpause = function() { title.removeAttribute('hidden') };
  412. video.onplay = function() { title.setAttribute('hidden', true) };
  413. }
  414. video.onloadeddata = function(e) {
  415. pauseOtherVideos(this);
  416. div.style.cssText += 'contain:none!important'; // allow fullscreen
  417. div.firstElementChild.appendChild(this);
  418. this.style.opacity = 1;
  419. var img = $(div, 'img');
  420. img.style.transition = 'opacity 1s';
  421. img.style.opacity = 0;
  422. };
  423. }
  424.  
  425. function switchToIFrame(e) {
  426. var div = this;
  427. var wrapper = div.firstElementChild;
  428. if (e) {
  429. console.log('[FYTE] Direct linking canceled on %s, switching to IFRAME player', div.FYTE.srcEmbed);
  430. var video = e.target ? e.target.closest('video') : e.path && e.path[e.path.length-1];
  431. while (video.lastElementChild)
  432. video.lastElementChild.remove();
  433. }
  434.  
  435. wrapper.insertAdjacentHTML('beforeend',
  436. '<iframe class="instant-youtube-embed" allowtransparency="true" src="' +
  437. div.FYTE.srcEmbed.replace('http:', 'https:').replace('/v/', '/embed/') +
  438. (div.FYTE.srcEmbed.indexOf('?') > 0 ? '&' : '?') +
  439. 'html5=1' +
  440. '&autoplay=1' +
  441. '&autohide=2' +
  442. '&border=0' +
  443. '&controls=1' +
  444. '&fs=1' +
  445. '&showinfo=1' +
  446. '&ssl=1' +
  447. '&theme=dark' +
  448. '&enablejsapi=1' +
  449. '" frameborder="0" allowfullscreen width="' + div.clientWidth + '" height="' + div.clientHeight + '"></iframe>');
  450.  
  451. wrapper.lastElementChild.onload = function() {
  452. pauseOtherVideos(this);
  453. this.style.cssText = important(
  454. 'position:absolute; left:0; top:0; right:0; padding:0; margin:auto; opacity:1; transition:opacity 2s;');
  455.  
  456. var div = this.closest('.instant-youtube-container');
  457. div.setAttribute('iframe', '');
  458. div.style.cssText += 'contain:none!important'; // allow fullscreen
  459. setTimeout(function() {
  460. $(div, 'img').style.display = 'none';
  461. var title = $(div, '.instant-youtube-title');
  462. if (title)
  463. title.remove();
  464. }, 2000);
  465. };
  466. }
  467.  
  468. function pauseOtherVideos(activePlayer) {
  469. [].forEach.call(activePlayer.ownerDocument.getElementsByClassName('instant-youtube-embed'), function(v) {
  470. if (v == activePlayer)
  471. return;
  472. switch (v.localName) {
  473. case 'video':
  474. if (!v.paused)
  475. v.pause();
  476. break;
  477. case 'iframe':
  478. try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {}
  479. break;
  480. }
  481. });
  482. }
  483.  
  484. function showOptions(e) {
  485. var optionsButton = e.target;
  486. optionsButton.insertAdjacentHTML('afterend', '\
  487. <div class="instant-youtube-options">\
  488. <label>Size:<br>\
  489. <select data-action="size-mode">\
  490. <option>Original</option>\
  491. <option>Fit to width</option>\
  492. <option>360p</option>\
  493. <option>480p</option>\
  494. <option>720p</option>\
  495. <option>1080p</option>\
  496. <option value="Custom">Custom...</option>\
  497. </select>\
  498. </label>\
  499. <label data-action="size-custom" ' + (resizeMode != 'Custom' ? 'disabled' : '') + '>\
  500. <input type="number" min="320" max="9999" placeholder="width" step="10" value="' + (resizeWidth||'') + '">\
  501. x\
  502. <input type="number" min="240" max="9999" placeholder="height" step="10" value="' + (resizeHeight||'') + '">\
  503. </label>\
  504. <label title="Show 3 thumbnails on mouse hover: at 25%, 50%, 75% of video duration">\
  505. <input data-action="storyboard" type="checkbox" ' + (showStoryboard ? 'checked' : '') + '>\
  506. Storyboard thumbs\
  507. </label>\
  508. <label title="Tip: shift-clicking thumbnails will use alternative player">\
  509. <input data-action="direct" type="checkbox" ' + (playHTML5 ? 'checked' : '') + '>\
  510. Play directly\
  511. </label>\
  512. <label title="Do not process customized videos with enablejsapi=1 parameter (requires page reload)">\
  513. <input data-action="safe" type="checkbox" ' + (skipCustom ? 'checked' : '') + '>\
  514. Safe\
  515. </label>\
  516. <span data-action="buttons">\
  517. <button>OK</button>\
  518. <button>Cancel</button>\
  519. </span>\
  520. </div>\
  521. ');
  522. var options = optionsButton.nextElementSibling;
  523.  
  524. options.addEventListener('keydown', function(e) {
  525. if (e.target.localName == 'input' &&
  526. !e.shiftKey && !e.altKey && !e.metaKey && !e.ctrlKey && e.key.match(/[.,]/))
  527. return false;
  528. });
  529.  
  530. $(options, '[data-action="size-mode"]').value = resizeMode;
  531. $(options, '[data-action="size-mode"]').addEventListener('change', function() {
  532. var v = this.value != 'Custom';
  533. var e = $(options, '[data-action="size-custom"]');
  534. e.children[0].disabled = e.children[1].disabled = v;
  535. v ? e.setAttribute('disabled', '') : e.removeAttribute('disabled');
  536. });
  537.  
  538. $(options, '[data-action="buttons"]').addEventListener('click', function(e) {
  539. if (e.target.textContent != 'OK') {
  540. options.remove();
  541. return;
  542. }
  543. var v, shouldAdjust;
  544. if (resizeMode != (v = $(options, '[data-action="size-mode"]').value)) {
  545. GM_setValue('resize', resizeMode = v);
  546. shouldAdjust = true;
  547. }
  548. if (resizeMode == 'Custom') {
  549. var w = $(options, '[placeholder="width"]').value |0;
  550. var h = $(options, '[placeholder="height"]').value |0;
  551. if (resizeWidth != w || resizeHeight != h) {
  552. updateCustomSize(w, h);
  553. GM_setValue('width', resizeWidth);
  554. GM_setValue('height', resizeHeight);
  555. shouldAdjust = true;
  556. }
  557. }
  558. if (showStoryboard != (v = $(options, '[data-action="storyboard"]').checked)) {
  559. GM_setValue('showStoryboard', showStoryboard = v);
  560. if (showStoryboard)
  561. $$('.instant-youtube-container').forEach(attachHoverHandlerIfNeeded);
  562. }
  563. if (playHTML5 != (v = $(options, '[data-action="direct"]').checked)) {
  564. GM_setValue('playHTML5', playHTML5 = v);
  565. $$('.instant-youtube-container .instant-youtube-link').forEach(function(e) {
  566. e.textContent = playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)';
  567. });
  568. }
  569. if (skipCustom != (v = $(options, '[data-action="safe"]').checked)) {
  570. GM_setValue('skipCustom', skipCustom = v);
  571. initEmbedSelector();
  572. }
  573.  
  574. options.remove();
  575.  
  576. if (shouldAdjust)
  577. adjustNodes(e, e.target.closest('.instant-youtube-container'));
  578. });
  579. }
  580.  
  581. function updateCustomSize(w, h) {
  582. resizeWidth = Math.min(9999, Math.max(320, w|0 || resizeWidth|0));
  583. resizeHeight = Math.min(9999, Math.max(240, h|0 || resizeHeight|0));
  584. }
  585.  
  586. function important(cssText) {
  587. return cssText.replace(/;/g, '!important;');
  588. }
  589.  
  590. function tryCatch(func) {
  591. try {
  592. return func();
  593. } catch(e) {
  594. console.log(e);
  595. }
  596. }
  597.  
  598. function injectStylesIfNeeded() {
  599. if (document.head.innerHTML.indexOf('.instant-youtube-container') > 0)
  600. return;
  601. GM_addStyle(important('\
  602. .instant-youtube-container {contain:strict; position:relative; overflow:hidden; cursor:pointer; background-color:black; padding:0; margin:0; font:normal 14px/1.0 sans-serif,Arial,Helvetica,Verdana; text-align:center;}\
  603. .instant-youtube-container .instant-youtube-wrapper {width:100%; height:100%;}\
  604. .instant-youtube-container .instant-youtube-play-button {position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; width:85px; height:60px; display:block;}\
  605. .instant-youtube-container .instant-youtube-loading-button {position:absolute; left:0; right:0; top:0; bottom:0; padding:0; margin:auto; display:block; width:20px; height:20px; background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==");}\
  606. .instant-youtube-container:hover .ytp-large-play-button-svg {fill:#CC181E;}\
  607. .instant-youtube-container .instant-youtube-link {\
  608. position:absolute; top:50%; left:0; right:0; width:20em; height:20px; margin:60px auto; padding:0; border:none; \
  609. display:block; text-align:center; text-decoration:none; color:white; text-shadow:1px 1px 3px black; font-weight:bold;\
  610. }\
  611. .instant-youtube-container span.instant-youtube-link {font-weight:normal; font-size:12px;}\
  612. .instant-youtube-container .instant-youtube-link:hover {color:white; text-decoration:underline; background:transparent;}\
  613. .instant-youtube-container iframe {z-index:10;}\
  614. .instant-youtube-container .instant-youtube-title {\
  615. display:block; z-index:9; background-color:rgba(0,0,0,0.5); color:white;\
  616. width:100%; top:0; left:0; right:0; position:absolute; z-index: 9;\
  617. color:white; text-shadow:1px 1px 2px black; text-align:center; text-decoration:none;\
  618. margin:0; padding:7px; border:none;\
  619. }\
  620. .instant-youtube-container .instant-youtube-title strong {font:bold 14px/1.0 sans-serif,Arial,Helvetica,Verdana;}\
  621. .instant-youtube-container .instant-youtube-title strong:after {content:" - watch on Youtube"; font-weight:normal; margin-right:1ex;}\
  622. .instant-youtube-container .instant-youtube-title span {color:inherit;}\
  623. .instant-youtube-container .instant-youtube-title span:before {content:"(";}\
  624. .instant-youtube-container .instant-youtube-title span:after {content:")";}\
  625. \
  626. @-webkit-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  627. @-moz-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  628. @keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  629. \
  630. .instant-youtube-container:not(:hover) .instant-youtube-title[hidden] {display:none; margin:0;}\
  631. .instant-youtube-container .instant-youtube-title:hover {text-decoration:underline;}\
  632. .instant-youtube-container .instant-youtube-title strong {color:white;}\
  633. \
  634. .instant-youtube-container .instant-youtube-options-button {position:absolute; right:0; bottom:0; color:white; font-size:11px; text-shadow:1px 1px 2px black; padding:1.5ex 2ex; margin:0; opacity:0.6;}\
  635. .instant-youtube-container .instant-youtube-options-button:hover {opacity:1; background:rgba(0,0,0,0.5);}\
  636. \
  637. .instant-youtube-container .instant-youtube-options {position:absolute; right:0; bottom:0; color:white; background:black; padding:2ex 1ex 2ex 2ex; margin:0; opacity:1; display:flex; flex-direction:column; align-items:flex-start; line-height:1.5; text-align:left;}\
  638. .instant-youtube-container .instant-youtube-options * {color:white; background:black; font:inherit; font-size:13px; vertical-align:middle; padding:0; margin:0; height:auto; width:auto; text-transform:none; text-align:left; border-radius:0; text-decoration:none;}\
  639. .instant-youtube-container .instant-youtube-options > label {margin-top:1ex;}\
  640. .instant-youtube-container .instant-youtube-options > label > * {display:inline;}\
  641. .instant-youtube-container .instant-youtube-options select {-webkit-appearance:menulist;}\
  642. .instant-youtube-container .instant-youtube-options [data-action="size-custom"] input {width:9ex; border:1px solid #666; padding:.5ex .5ex .4ex;}\
  643. .instant-youtube-container .instant-youtube-options [data-action="buttons"] {margin-top:1em;}\
  644. .instant-youtube-container .instant-youtube-options button {padding:.5ex 2ex; margin:0 1ex 0 0; border:2px solid gray; font-weight:bold;}\
  645. .instant-youtube-container .instant-youtube-options button:hover {border-color:white;}\
  646. .instant-youtube-container .instant-youtube-options > [disabled] {opacity:0.25;}\
  647. \
  648. .instant-youtube-container .instant-youtube-storyboard {position:absolute; display:none; flex-direction:row; left:0; right:0; bottom:10px; max-height:33%;}\
  649. .instant-youtube-container:hover .instant-youtube-storyboard {display:flex;}\
  650. .instant-youtube-container .instant-youtube-storyboard div {flex:auto;}\
  651. .instant-youtube-container .instant-youtube-storyboard img {border:3px solid rgba(255,255,255,.5); box-shadow:2px 2px 10px black; max-height:100%; width:auto!important;}\
  652. '));
  653. }

QingJ © 2025

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