Lazy Embedded Video

Lazy load embedded videos from Youtube/Dailymotion/Vimeo/Rutube/Twitch/Coub

当前为 2024-09-28 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Lazy Embedded Video
  3. // @namespace zeusex81@gmail.com
  4. // @description Lazy load embedded videos from Youtube/Dailymotion/Vimeo/Rutube/Twitch/Coub
  5. // @version 4.2
  6. // @include *
  7. // @icon https://i.imgur.com/rf0mFDM.png
  8. // @license MIT
  9. // @grant GM.getValue
  10. // @grant GM.setValue
  11. // @grant GM_getValue
  12. // @grant GM_setValue
  13. // @run-at document-start
  14. // ==/UserScript==
  15.  
  16. (async function() {
  17. var a = document.createElement("A");
  18. try { a.href = top.location.href; }
  19. catch(e) { a.href = document.referrer || location.href; }
  20. if(a.hostname && /(youtube|dailymotion|vimeo|rutube|twitch|coub)\.[^.]+$/.test(a.hostname))
  21. return;
  22. var getValue = typeof(GM) != "undefined" ? GM.getValue : typeof(GM_getValue) != "undefined" ? GM_getValue :
  23. function(name, value) { return localStorage.getItem(name) || value; };
  24. var setValue = typeof(GM) != "undefined" ? GM.setValue : typeof(GM_setValue) != "undefined" ? GM_setValue :
  25. function(name, value) { localStorage.setItem(name, value); };
  26.  
  27. var settings = JSON.parse(await getValue("zeusLEV", '[false,true,[]]'));
  28. while(typeof(settings) == "string") settings = JSON.parse(settings);
  29. if(settings[2].includes(location.hostname))
  30. return;
  31.  
  32. var listener = false;
  33. var createListener = function() {
  34. if(listener) return;
  35. listener = true;
  36. window.addEventListener("message", async function(e) {
  37. if(!e.data.startsWith("lazyVideo")) return;
  38. var data = e.data.split(' ');
  39. switch(data[1]) {
  40. case "CSP" : iframes[parseInt(data[2])].dataset.lazyVideo = 3; break;
  41. case "play" : iframes[parseInt(data[2])].removeAttribute("srcdoc");
  42. iframes[parseInt(data[2])].src = data[3]; break;
  43. case "settings" :
  44. settings = JSON.parse(await getValue("zeusLEV", '[false,true,[]]'));
  45. while(typeof(settings) == "string") settings = JSON.parse(settings);
  46. switch(data[2]) {
  47. case "autoplay" : settings[0] = data[3] == 'true'; break;
  48. case "flash" : settings[1] = data[3] == 'true'; break;
  49. case "reset" : settings[2] = []; break;
  50. case "whitelist" :
  51. observer.disconnect();
  52. cancelAnimationFrame(animation);
  53. if(!settings[2].includes(location.hostname))
  54. settings[2].push(location.hostname);
  55. for(var i = 0; i < iframes.length; i++)
  56. iframes[i].removeAttribute("srcdoc");
  57. break;
  58. }
  59. setValue("zeusLEV", JSON.stringify(settings));
  60. break;
  61. }
  62. });
  63. }
  64.  
  65. var html, iframes = [];
  66. var createHtml = function(url, src, api, background_img) {
  67. /(.*\/\/(?:[^.\/]+\.)?([^.\/]+)\.[^.\/]+)\//i.test(url);
  68. var provider_url = RegExp.$1, provider_name = RegExp.$2, data_convert = "", button_color = "";
  69. if(api) api += '&callback=jsonpCallback';
  70. switch(provider_name) {
  71. case "youtube" :
  72. button_color = "#c22";
  73. data_convert += 'data = {'+
  74. 'thumbnail_url: (data.items[0].snippet.thumbnails.maxres || data.items[0].snippet.thumbnails.standard || '+
  75. 'data.items[0].snippet.thumbnails.high || data.items[0].snippet.thumbnails.medium || '+
  76. 'data.items[0].snippet.thumbnails.default).url,'+
  77. 'title: data.items[0].snippet.title,'+
  78. 'author_url: "https://www.youtube.com/channel/"+data.items[0].snippet.channelId,'+
  79. 'author_name: data.items[0].snippet.channelTitle,'+
  80. 'duration: data.items[0].contentDetails ? /PT(\\d+H)?(\\d+M)?(\\d+S)?/i.test(data.items[0].contentDetails.duration) && '+
  81. '(parseInt(RegExp.$1||0)*3600+parseInt(RegExp.$2||0)*60+parseInt(RegExp.$3||0)) || "LIVE" : "PLAYLIST"'+
  82. '};';
  83. break;
  84. case "dailymotion" :
  85. button_color = "#fd5";
  86. data_convert += 'data.author_url = data["owner.url"];'+
  87. 'data.author_name = data["owner.screenname"];'+
  88. 'if(!data.duration) data.duration = "LIVE";';
  89. break;
  90. case "vimeo" :
  91. button_color = "#5af";
  92. data_convert += 'if(data.thumbnail_url) data.thumbnail_url = data.thumbnail_url.replace(/_\\d+x\\d+/i, "");';
  93. break;
  94. case "rutube" :
  95. button_color = "#444";
  96. data_convert += 'if(data.thumbnail_url) data.thumbnail_url = data.thumbnail_url.replace(/\\?.+/i, "");';
  97. break;
  98. case "twitch" :
  99. button_color = "#548";
  100. break;
  101. case "coub" :
  102. button_color = "#04f";
  103. data_convert += 'if(data.channel_url) data.author_url = data.channel_url;';
  104. break;
  105. }
  106. if(!html) html = [
  107. '<!doctype html>'+
  108. '<html>'+
  109. '<head>'+
  110. '<title>Lazy Embedded Video</title>'+
  111. '<style>'+
  112. 'html { height:100%; } '+
  113. 'body { margin:0; height:100%; color:white; font:14px sans-serif; '+
  114. '--thumbnail_url:', background_img, '; background:black var(--thumbnail_url) center/100% no-repeat; } '+
  115. 'a { color:inherit; font-weight:bold; text-decoration:none; } '+
  116. 'a:hover { text-decoration:underline; } '+
  117. '#interface { position:absolute; width:100%; height:100%; overflow:hidden; opacity:0.9; '+
  118. '-moz-user-select:none; -webkit-user-select:none; -ms-user-select:none; user-select:none; } '+
  119. '#playButton { display:flex; height:100%; cursor:pointer; } '+
  120. '#playButton > div { width:70px; height:70px; margin:auto; border-radius:50%; background-color:black; } '+
  121. '#playButton:hover > div { background-color:', button_color, '; } '+
  122. '#playButton > div > div { width:0; height:0; margin:20px 0 0 25px; border:solid transparent; '+
  123. 'border-width:14px 0px 14px 28px; border-left-color:white; } '+
  124. '#infobar { position:absolute; top:0px; width:100%; height:32px; display:flex; '+
  125. 'box-sizing:border-box; background:black; border:0px solid grey; border-bottom-width:1px; } '+
  126. '#author, #title, #duration { overflow:hidden; white-space:nowrap; margin:auto 8px; } '+
  127. '#author { flex-shrink:0; max-width:30%; color:', button_color ,'; } '+
  128. '#space { flex-grow:1; } '+
  129. '#duration { flex-shrink:0; } '+
  130. '#settingsButton { flex-basis:32px; flex-shrink:0; font:bold 20px sans-serif; text-align:center; cursor:pointer; } '+
  131. '#settingsButton:hover { color:', button_color, '; } '+
  132. '#settingsButton.active { background-color:', button_color, '; color:black; } '+
  133. '#settingsPanel { position:absolute; right:0px; top:31px; max-height:100%; margin:0px; list-style:none; padding:8px; '+
  134. 'border:solid grey; border-width:0px 0px 1px 1px; background-color:', button_color ,'; color:black; cursor:default; visibility:hidden; } '+
  135. '#settingsPanel.active { visibility:visible; } '+
  136. '#settingsPanel label { display:inline-block; width:144px; vertical-align:top; } '+
  137. '#settingsPanel button { width:100%; }'+
  138. '</style>'+
  139. '</head>'+
  140. '<body>'+
  141. '<div id=interface>'+
  142. '<div id=playButton><div><div></div></div></div>'+
  143. '<div id=infobar>'+
  144. '<a id=author target=_blank onmouseenter="this.title = this.scrollWidth > this.clientWidth ? this.textContent : \'\';" href="', provider_url, '">', provider_name, '</a>'+
  145. '<a id=title target=_blank onmouseenter="this.title = this.scrollWidth > this.clientWidth ? this.textContent : \'\';" href="', url, '">', url, '</a>'+
  146. '<div id=space></div>'+
  147. '<span id=settingsButton>⚙</span>'+
  148. '</div>'+
  149. '<ul id=settingsPanel>'+
  150. '<li><label>Allow autoplay:</label><input class=setting type=checkbox', '', '></li>'+
  151. '<li><label>Legacy Flash support:</label><input class=setting type=checkbox', '', '></li>'+
  152. '<li><button class=setting>Whitelist this site</button>'+
  153. '<li><button class=setting>Clear whitelist</button>'+
  154. '</ul>'+
  155. '</div>'+
  156. '<script>'+
  157. 'parent.postMessage("lazyVideo CSP ', iframes.length, '", "'+location.href+'");'+
  158. 'document.getElementById("playButton").onclick = function() {'+
  159. 'parent.postMessage("lazyVideo play ', iframes.length, ' ', src, '", "'+location.href+'");'+
  160. '};'+
  161. 'var settingsButton = document.getElementById("settingsButton");'+
  162. 'var settingsPanel = document.getElementById("settingsPanel");'+
  163. 'settingsButton.onclick = function() {'+
  164. 'settingsButton.classList.toggle("active");'+
  165. 'settingsPanel.classList.toggle("active");'+
  166. '};'+
  167. '[].slice.call(settingsPanel.getElementsByClassName("setting")).forEach(function(e, i) {'+
  168. 'switch(i) {'+
  169. 'case 0: e.onchange = function() { parent.postMessage("lazyVideo settings autoplay "+e.checked, "'+location.href+'"); }; break;'+
  170. 'case 1: e.onchange = function() { parent.postMessage("lazyVideo settings flash "+e.checked , "'+location.href+'"); }; break;'+
  171. 'case 2: e.onclick = function() { parent.postMessage("lazyVideo settings whitelist" , "'+location.href+'"); }; break;'+
  172. 'case 3: e.onclick = function() { parent.postMessage("lazyVideo settings reset" , "'+location.href+'"); }; break;'+
  173. '}'+
  174. '});'+
  175. 'function removeProtocol(url) { return url.replace(/^[a-z]+:/i, ""); }'+
  176. 'function jsonpCallback(data) {',
  177. data_convert,
  178. 'if(data.thumbnail_url) document.body.style.setProperty("--thumbnail_url", "url("+data.thumbnail_url+")");'+
  179. 'if(data.thumbnail_url) document.body.style.setProperty("--darkreader-bgimg--thumbnail_url", "url("+data.thumbnail_url+")");'+
  180. 'if(data.url) document.getElementById("title").href = removeProtocol(data.url);'+
  181. 'if(data.title) document.getElementById("title").textContent = data.title;'+
  182. 'if(data.author_url) document.getElementById("author").href = removeProtocol(data.author_url);'+
  183. 'if(data.author_name) document.getElementById("author").textContent = data.author_name;'+
  184. 'if(data.duration) document.getElementById("space").insertAdjacentHTML("afterend",'+
  185. '"<div id=duration>"+(Number(data.duration) ? new Date(data.duration*1000).toISOString().substr(11,8) : data.duration)+"</div>");'+
  186. '}'+
  187. '</script>'+
  188. '<script id=api src="', api, '"></script>'+
  189. '</body>'+
  190. '</html>'
  191. ];
  192. html[ 1] = background_img || 'none';
  193. html[ 3] = button_color;
  194. html[ 5] = button_color;
  195. html[ 7] = button_color;
  196. html[ 9] = button_color;
  197. html[11] = button_color;
  198. html[13] = provider_url;
  199. html[15] = provider_name;
  200. html[17] = url;
  201. html[19] = url;
  202. html[21] = settings[0] ? ' checked' : '';
  203. html[23] = settings[1] ? ' checked' : '';
  204. html[25] = iframes.length;
  205. html[27] = iframes.length;
  206. html[29] = src;
  207. html[31] = data_convert;
  208. html[33] = api;
  209. };
  210.  
  211. var createOembed = function(api, url) { return api+encodeURIComponent(url); };
  212. // var createNOembed = function(api, url) { return createOembed("https://noembed.com/embed?url=", url); };
  213. var createJOembed = function(api, url) { return createOembed("https://json2jsonp.com/?url=", createOembed(api, url)); };
  214.  
  215. var createLazyVideo = function(elem) {
  216. var id, args = "", url, src = a.href = elem.src || elem.data || elem.dataset.src;
  217. if(!a.hostname || elem.dataset.lazyVideo) return;
  218. elem.dataset.lazyVideo = 1;
  219. switch(a.hostname.match(/([^.]+)\.[^.]+$/)[1]) {
  220. case "youtube" :
  221. case "youtube-nocookie" :
  222. if(/\/(?:p\/|embed\/videoseries)([^&]*)/i.test(a.pathname)) {
  223. id = RegExp.$1 || (/[?&]list=([^&]+)/i.test(a.search) && RegExp.$1);
  224. if(!id || (settings[0] && a.search.includes("autoplay=1"))) return;
  225. if(/[?&](v=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  226. if(/[?&](index=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  227. if(/[?&](start=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  228. createHtml(
  229. url = /[?&]v=([^&]+)/i.test(a.search) ? "https://www.youtube.com/watch?list="+id+args : "https://www.youtube.com/playlist?list="+id,
  230. src = "https://www.youtube-nocookie.com/embed/videoseries?autoplay=1&list="+id+args,
  231. "https://www.googleapis.com/youtube/v3/playlists?part=snippet&fields=items/snippet(channelId,title,thumbnails,channelTitle)&key=AIzaSyBJ-o6n51GQ6jEqjvEN0bI1KdX5CHZQy5E&id="+id,
  232. /[?&]v=([^&]+)/i.test(a.search) ? "url(https://i.ytimg.com/vi/"+RegExp.$1+"/hqdefault.jpg)" : null
  233. );
  234. } else {
  235. if(/\/(?:v|embed)\/([^&]*)/i.test(a.pathname)) id = RegExp.$1 || (/[?&]v=([^&]+)/i.test(a.search) && RegExp.$1);
  236. if(!id || (settings[0] && a.search.includes("autoplay=1"))) return;
  237. if(/[?&](start=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  238. createHtml(
  239. url = "https://www.youtube.com/watch?v="+id+args,
  240. src = "https://www.youtube-nocookie.com/embed/"+id+"?autoplay=1"+args,
  241. // createNOembed("https://www.youtube.com/oembed?format=json&url=", url),
  242. "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&fields=items(snippet(channelId,title,thumbnails,channelTitle),contentDetails/duration)&key=AIzaSyBJ-o6n51GQ6jEqjvEN0bI1KdX5CHZQy5E&id="+id,
  243. "url(https://i.ytimg.com/vi/"+id+"/hqdefault.jpg)"
  244. );
  245. }
  246. break;
  247. case "dailymotion" :
  248. if(/\/(?:swf|embed)\/(?:video\/)?([^&_]+)/i.test(a.pathname)) id = RegExp.$1;
  249. if(!id || (settings[0] && a.search.includes("autoplay=1"))) return;
  250. // if(/[?&](mute=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  251. if(/[?&](start=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  252. createHtml(
  253. url = "https://www.dailymotion.com/video/"+id+"?"+args,
  254. src = "https://www.dailymotion.com/embed/video/"+id+"?autoplay=1"+args,
  255. // createOembed("https://www.dailymotion.com/services/oembed?format=json&url=", url),
  256. "https://api.dailymotion.com/video/"+id+"?fields=owner.screenname,owner.url,title,url,duration,thumbnail_url",
  257. "url(https://www.dailymotion.com/thumbnail/video/"+id+")"
  258. );
  259. break;
  260. case "vimeo" :
  261. if(/\/(?:moogaloop\.swf|video\/)([^&]*)/i.test(a.pathname))
  262. id = RegExp.$1 || (/[?&]clip_id=([^&]+)/i.test(a.search) && RegExp.$1);
  263. if(!id || (settings[0] && a.search.includes("autoplay=1"))) return;
  264. if(/[?&](loop=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  265. if(/(\#t=[\dhms]+)/i.test(a.hash)) args += RegExp.$1;
  266. createHtml(
  267. url = "https://vimeo.com/"+id+"?"+args,
  268. src = "https://player.vimeo.com/video/"+id+"?autoplay=1"+args,
  269. createOembed("https://vimeo.com/api/oembed.json?url=", url)
  270. );
  271. break;
  272. case "rutube" :
  273. if(/(?:\/play)?\/embed\/([^&.\/]+)/i.test(a.pathname)) id = RegExp.$1;
  274. else if(/[?&]pl_video=([^&]+)/i.test(a.search)) id = RegExp.$1;
  275. if(!id || (settings[0] && a.search.includes("autoStart=1"))) return;
  276. if(/[?&](bmstart=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  277. createHtml(
  278. url = "https://rutube.ru/"+(isNaN(id) ? "video/"+id+"/" : "tracks/"+id+".html"),
  279. src = "https://rutube.ru/"+(a.pathname.includes("/embed/") ? "play/embed/"+id+"?autoStart=1"+args : "pl/?pl_video="+id),
  280. createJOembed("https://rutube.ru/api/oembed/?format=json&url=", url)
  281. );
  282. break;
  283. case "twitch" :
  284. if(/(channel|video|clip)=([^&]+)/i.test(a.search)) {args = RegExp.$1; id = RegExp.$2;}
  285. else if(/(stream=.+&channelId)=([^&]+)/i.test(a.search)) {args = RegExp.$1; id = RegExp.$2;}
  286. else if(/\/(.+)\/embed/i.test(a.pathname)) {args = "channel"; id = RegExp.$1;}
  287. if(!id || (settings[0] && a.search.includes("autoplay=true"))) return;
  288. createHtml(
  289. url = "https://"+(args=="clip" ? "clips" : "www")+".twitch.tv/"+(args=="video" ? "videos/" : "")+id,
  290. src = a.href.split('?')[0]+"?autoplay=true&"+args+"="+id+"&parent="+location.hostname,
  291. null,
  292. "url(https://static-cdn.jtvnw.net/previews-ttv/live_user_"+(args=="channel" ? id : 0)+"-0x0.jpg)"
  293. );
  294. break;
  295. case "coub" :
  296. if(/\/embed\/([^&]+)/i.test(a.pathname)) id = RegExp.$1;
  297. if(!id || (settings[0] && a.search.includes("autostart=true"))) return;
  298. createHtml(
  299. url = "https://coub.com/view/"+id,
  300. src = "https://coub.com/embed/"+id+"?startWithHD=true&autostart=true",
  301. createJOembed("https://coub.com/api/oembed.json?url=", url)
  302. );
  303. break;
  304. default :
  305. return;
  306. }
  307. if(elem.tagName != "IFRAME") {
  308. if(elem.parentNode.tagName == "OBJECT")
  309. elem = elem.parentNode;
  310. var iframe = document.createElement("IFRAME");
  311. iframe.src = src;
  312. iframe.id = elem.id;
  313. iframe.name = elem.name;
  314. iframe.className = elem.className;
  315. iframe.style.cssText = elem.style.cssText;
  316. iframe.width = elem.width;
  317. iframe.height = elem.height;
  318. iframe.frameBorder = elem.border;
  319. iframe.align = elem.align;
  320. elem.parentNode.replaceChild(iframe, elem);
  321. elem = iframe;
  322. }
  323. createListener();
  324. elem.dataset.lazyVideo = 2;
  325. elem.allowFullscreen = true;
  326. elem.srcdoc = html.join("");
  327. iframes.push(elem);
  328. setTimeout(function() {
  329. if(elem.dataset.lazyVideo != 3)
  330. elem.removeAttribute("srcdoc");
  331. }, 15000);
  332. };
  333.  
  334. var observer, animation;
  335. var update = function() {
  336. if(!document.body) {
  337. animation = requestAnimationFrame(update);
  338. } else if(!observer) {
  339. observer = new MutationObserver(function() { if(!animation) animation = requestAnimationFrame(update); });
  340. observer.observe(document.body, {childList: true, attributes: false, characterData: false, subtree: true});
  341. animation = requestAnimationFrame(update);
  342. } else {
  343. var nodes = document.querySelectorAll(settings[1] ? "IFRAME, EMBED, OBJECT" : "IFRAME");
  344. for(var i = 0; i < nodes.length; i++)
  345. createLazyVideo(nodes[i]);
  346. animation = null;
  347. }
  348. };
  349. update();
  350. })();

QingJ © 2025

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