Lazy Embedded Video

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

当前为 2024-04-13 提交的版本,查看 最新版本

  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.0
  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. '<meta name="darkreader">'+
  112. '<style>'+
  113. 'html { height:100%; } '+
  114. 'body { margin:0; height:100%; color:white; font:14px sans-serif; '+
  115. 'background:black center/100% no-repeat; } '+
  116. 'a { color:inherit; font-weight:bold; text-decoration:none; } '+
  117. 'a:hover { text-decoration:underline; } '+
  118. '#interface { position:absolute; width:100%; height:100%; overflow:hidden; opacity:0.9; '+
  119. '-moz-user-select:none; -webkit-user-select:none; -ms-user-select:none; user-select:none; } '+
  120. '#playButton { display:flex; height:100%; cursor:pointer; } '+
  121. '#playButton > div { width:70px; height:70px; margin:auto; border-radius:50%; background-color:black; } '+
  122. '#playButton:hover > div { background-color:', button_color, '; } '+
  123. '#playButton > div > div { width:0; height:0; margin:20px 0 0 25px; border:solid transparent; '+
  124. 'border-width:14px 0px 14px 28px; border-left-color:white; } '+
  125. '#infobar { position:absolute; top:0px; width:100%; height:32px; display:flex; '+
  126. 'box-sizing:border-box; background:black; border:0px solid grey; border-bottom-width:1px; } '+
  127. '#author, #title, #duration { overflow:hidden; white-space:nowrap; margin:auto 8px; } '+
  128. '#author { flex-shrink:0; max-width:30%; color:', button_color ,'; } '+
  129. '#space { flex-grow:1; } '+
  130. '#duration { flex-shrink:0; } '+
  131. '#settingsButton { flex-basis:32px; flex-shrink:0; font:bold 20px sans-serif; text-align:center; cursor:pointer; } '+
  132. '#settingsButton:hover { color:', button_color, '; } '+
  133. '#settingsButton.active { background-color:', button_color, '; color:black; } '+
  134. '#settingsPanel { position:absolute; right:0px; top:31px; max-height:100%; margin:0px; list-style:none; padding:8px; '+
  135. 'border:solid grey; border-width:0px 0px 1px 1px; background-color:', button_color ,'; color:black; cursor:default; visibility:hidden; } '+
  136. '#settingsPanel.active { visibility:visible; } '+
  137. '#settingsPanel label { display:inline-block; width:144px; vertical-align:top; } '+
  138. '#settingsPanel button { width:100%; }'+
  139. '</style>'+
  140. '</head>'+
  141. '<body>'+
  142. '<div id=interface>'+
  143. '<div id=playButton><div><div></div></div></div>'+
  144. '<div id=infobar>'+
  145. '<a id=author target=_blank onmouseenter="this.title = this.scrollWidth > this.clientWidth ? this.textContent : \'\';" href="', provider_url, '">', provider_name, '</a>'+
  146. '<a id=title target=_blank onmouseenter="this.title = this.scrollWidth > this.clientWidth ? this.textContent : \'\';" href="', url, '">', url, '</a>'+
  147. '<div id=space></div>'+
  148. '<span id=settingsButton>⚙</span>'+
  149. '</div>'+
  150. '<ul id=settingsPanel>'+
  151. '<li><label>Allow autoplay:</label><input class=setting type=checkbox', '', '></li>'+
  152. '<li><label>Legacy Flash support:</label><input class=setting type=checkbox', '', '></li>'+
  153. '<li><button class=setting>Whitelist this site</button>'+
  154. '<li><button class=setting>Clear whitelist</button>'+
  155. '</ul>'+
  156. '</div>'+
  157. '<script>'+
  158. 'parent.postMessage("lazyVideo CSP ', iframes.length, '", "'+location.href+'");'+
  159. 'document.getElementById("playButton").onclick = function() {'+
  160. 'parent.postMessage("lazyVideo play ', iframes.length, ' ', src, '", "'+location.href+'");'+
  161. '};'+
  162. 'var settingsButton = document.getElementById("settingsButton");'+
  163. 'var settingsPanel = document.getElementById("settingsPanel");'+
  164. 'settingsButton.onclick = function() {'+
  165. 'settingsButton.classList.toggle("active");'+
  166. 'settingsPanel.classList.toggle("active");'+
  167. '};'+
  168. '[].slice.call(settingsPanel.getElementsByClassName("setting")).forEach(function(e, i) {'+
  169. 'switch(i) {'+
  170. 'case 0: e.onchange = function() { parent.postMessage("lazyVideo settings autoplay "+e.checked, "'+location.href+'"); }; break;'+
  171. 'case 1: e.onchange = function() { parent.postMessage("lazyVideo settings flash "+e.checked , "'+location.href+'"); }; break;'+
  172. 'case 2: e.onclick = function() { parent.postMessage("lazyVideo settings whitelist" , "'+location.href+'"); }; break;'+
  173. 'case 3: e.onclick = function() { parent.postMessage("lazyVideo settings reset" , "'+location.href+'"); }; break;'+
  174. '}'+
  175. '});'+
  176. 'var loaded = false;'+
  177. 'function removeProtocol(url) { return url.replace(/^[a-z]+:/i, ""); }'+
  178. 'function jsonpCallback(data) {',
  179. data_convert,
  180. 'loaded = true;'+
  181. 'if(data.thumbnail_url) document.body.style.backgroundImage = "url("+removeProtocol(data.thumbnail_url)+")";'+
  182. 'if(data.url) document.getElementById("title").href = removeProtocol(data.url);'+
  183. 'if(data.title) document.getElementById("title").textContent = data.title;'+
  184. 'if(data.author_url) document.getElementById("author").href = removeProtocol(data.author_url);'+
  185. 'if(data.author_name) document.getElementById("author").textContent = data.author_name;'+
  186. 'if(data.duration) document.getElementById("space").insertAdjacentHTML("afterend",'+
  187. '"<div id=duration>"+(Number(data.duration) ? new Date(data.duration*1000).toISOString().substr(11,8) : data.duration)+"</div>");'+
  188. '}'+
  189. '</script>'+
  190. '<script id=api src="', api, '"></script>'+
  191. '<script>'+
  192. 'if(!loaded)'+
  193. 'document.body.style.backgroundImage = "', background_img, '";'+
  194. '</script>'+
  195. '</body>'+
  196. '</html>'
  197. ];
  198. html[ 1] = button_color;
  199. html[ 3] = button_color;
  200. html[ 5] = button_color;
  201. html[ 7] = button_color;
  202. html[ 9] = button_color;
  203. html[11] = provider_url;
  204. html[13] = provider_name;
  205. html[15] = url;
  206. html[17] = url;
  207. html[19] = settings[0] ? ' checked' : '';
  208. html[21] = settings[1] ? ' checked' : '';
  209. html[23] = iframes.length;
  210. html[25] = iframes.length;
  211. html[27] = src;
  212. html[29] = data_convert;
  213. html[31] = api;
  214. html[33] = background_img;
  215. };
  216.  
  217. var createOembed = function(api, url) { return api+encodeURIComponent(url); };
  218. // var createNOembed = function(api, url) { return createOembed("https://noembed.com/embed?url=", url); };
  219. var createJOembed = function(api, url) { return createOembed("https://json2jsonp.com/?url=", createOembed(api, url)); };
  220.  
  221. var createLazyVideo = function(elem) {
  222. var id, args = "", url, src = a.href = elem.src || elem.data || elem.dataset.src;
  223. if(!a.hostname || elem.dataset.lazyVideo) return;
  224. elem.dataset.lazyVideo = 1;
  225. switch(a.hostname.match(/([^.]+)\.[^.]+$/)[1]) {
  226. case "youtube" :
  227. case "youtube-nocookie" :
  228. if(/\/(?:p\/|embed\/videoseries)([^&]*)/i.test(a.pathname)) {
  229. id = RegExp.$1 || (/[?&]list=([^&]+)/i.test(a.search) && RegExp.$1);
  230. if(!id || (settings[0] && a.search.includes("autoplay=1"))) return;
  231. if(/[?&](v=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  232. if(/[?&](index=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  233. if(/[?&](start=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  234. createHtml(
  235. url = /[?&]v=([^&]+)/i.test(a.search) ? "https://www.youtube.com/watch?list="+id+args : "https://www.youtube.com/playlist?list="+id,
  236. src = "https://www.youtube-nocookie.com/embed/videoseries?autoplay=1&list="+id+args,
  237. "https://www.googleapis.com/youtube/v3/playlists?part=snippet&fields=items/snippet(channelId,title,thumbnails,channelTitle)&key=AIzaSyDLowtdhRBblJhyDhtiPaIbwRKT_PSyHWE&id="+id,
  238. /[?&]v=([^&]+)/i.test(a.search) ? "url(https://i.ytimg.com/vi/"+RegExp.$1+"/hqdefault.jpg)" : null
  239. );
  240. } else {
  241. if(/\/(?:v|embed)\/([^&]*)/i.test(a.pathname)) id = RegExp.$1 || (/[?&]v=([^&]+)/i.test(a.search) && RegExp.$1);
  242. if(!id || (settings[0] && a.search.includes("autoplay=1"))) return;
  243. if(/[?&](start=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  244. createHtml(
  245. url = "https://www.youtube.com/watch?v="+id+args,
  246. src = "https://www.youtube-nocookie.com/embed/"+id+"?autoplay=1"+args,
  247. // createNOembed("https://www.youtube.com/oembed?format=json&url=", url),
  248. "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&fields=items(snippet(channelId,title,thumbnails,channelTitle),contentDetails/duration)&key=AIzaSyDLowtdhRBblJhyDhtiPaIbwRKT_PSyHWE&id="+id,
  249. "url(https://i.ytimg.com/vi/"+id+"/hqdefault.jpg)"
  250. );
  251. }
  252. break;
  253. case "dailymotion" :
  254. if(/\/(?:swf|embed)\/(?:video\/)?([^&_]+)/i.test(a.pathname)) id = RegExp.$1;
  255. if(!id || (settings[0] && a.search.includes("autoplay=1"))) return;
  256. // if(/[?&](mute=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  257. if(/[?&](start=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  258. createHtml(
  259. url = "https://www.dailymotion.com/video/"+id+"?"+args,
  260. src = "https://www.dailymotion.com/embed/video/"+id+"?autoplay=1"+args,
  261. // createOembed("https://www.dailymotion.com/services/oembed?format=json&url=", url),
  262. "https://api.dailymotion.com/video/"+id+"?fields=owner.screenname,owner.url,title,url,duration,thumbnail_url",
  263. "url(https://www.dailymotion.com/thumbnail/video/"+id+")"
  264. );
  265. break;
  266. case "vimeo" :
  267. if(/\/(?:moogaloop\.swf|video\/)([^&]*)/i.test(a.pathname))
  268. id = RegExp.$1 || (/[?&]clip_id=([^&]+)/i.test(a.search) && RegExp.$1);
  269. if(!id || (settings[0] && a.search.includes("autoplay=1"))) return;
  270. if(/[?&](loop=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  271. if(/(\#t=[\dhms]+)/i.test(a.hash)) args += RegExp.$1;
  272. createHtml(
  273. url = "https://vimeo.com/"+id+"?"+args,
  274. src = "https://player.vimeo.com/video/"+id+"?autoplay=1"+args,
  275. createOembed("https://vimeo.com/api/oembed.json?url=", url)
  276. );
  277. break;
  278. case "rutube" :
  279. if(/(?:\/play)?\/embed\/([^&.\/]+)/i.test(a.pathname)) id = RegExp.$1;
  280. else if(/[?&]pl_video=([^&]+)/i.test(a.search)) id = RegExp.$1;
  281. if(!id || (settings[0] && a.search.includes("autoStart=1"))) return;
  282. if(/[?&](bmstart=[^&]+)/i.test(a.search)) args += "&"+RegExp.$1;
  283. createHtml(
  284. url = "https://rutube.ru/"+(isNaN(id) ? "video/"+id+"/" : "tracks/"+id+".html"),
  285. src = "https://rutube.ru/"+(a.pathname.includes("/embed/") ? "play/embed/"+id+"?autoStart=1"+args : "pl/?pl_video="+id),
  286. createJOembed("https://rutube.ru/api/oembed/?format=json&url=", url)
  287. );
  288. break;
  289. case "twitch" :
  290. if(/(channel|video|clip)=([^&]+)/i.test(a.search)) {args = RegExp.$1; id = RegExp.$2;}
  291. else if(/(stream=.+&channelId)=([^&]+)/i.test(a.search)) {args = RegExp.$1; id = RegExp.$2;}
  292. else if(/\/(.+)\/embed/i.test(a.pathname)) {args = "channel"; id = RegExp.$1;}
  293. if(!id || (settings[0] && a.search.includes("autoplay=true"))) return;
  294. createHtml(
  295. url = "https://"+(args=="clip" ? "clips" : "www")+".twitch.tv/"+(args=="video" ? "videos/" : "")+id,
  296. src = a.href.split('?')[0]+"?autoplay=true&"+args+"="+id+"&parent="+location.hostname,
  297. null,
  298. "url(https://static-cdn.jtvnw.net/previews-ttv/live_user_"+(args=="channel" ? id : 0)+"-0x0.jpg)"
  299. );
  300. break;
  301. case "coub" :
  302. if(/\/embed\/([^&]+)/i.test(a.pathname)) id = RegExp.$1;
  303. if(!id || (settings[0] && a.search.includes("autostart=true"))) return;
  304. createHtml(
  305. url = "https://coub.com/view/"+id,
  306. src = "https://coub.com/embed/"+id+"?startWithHD=true&autostart=true",
  307. createJOembed("https://coub.com/api/oembed.json?url=", url)
  308. );
  309. break;
  310. default :
  311. return;
  312. }
  313. if(elem.tagName != "IFRAME") {
  314. if(elem.parentNode.tagName == "OBJECT")
  315. elem = elem.parentNode;
  316. var iframe = document.createElement("IFRAME");
  317. iframe.src = src;
  318. iframe.id = elem.id;
  319. iframe.name = elem.name;
  320. iframe.className = elem.className;
  321. iframe.style.cssText = elem.style.cssText;
  322. iframe.width = elem.width;
  323. iframe.height = elem.height;
  324. iframe.frameBorder = elem.border;
  325. iframe.align = elem.align;
  326. elem.parentNode.replaceChild(iframe, elem);
  327. elem = iframe;
  328. }
  329. createListener();
  330. elem.dataset.lazyVideo = 2;
  331. elem.allowFullscreen = true;
  332. elem.srcdoc = html.join("");
  333. iframes.push(elem);
  334. setTimeout(function() {
  335. if(elem.dataset.lazyVideo != 3)
  336. elem.removeAttribute("srcdoc");
  337. }, 15000);
  338. };
  339.  
  340. var observer, animation;
  341. var update = function() {
  342. if(!document.body) {
  343. animation = requestAnimationFrame(update);
  344. } else if(!observer) {
  345. observer = new MutationObserver(function() { if(!animation) animation = requestAnimationFrame(update); });
  346. observer.observe(document.body, {childList: true, attributes: false, characterData: false, subtree: true});
  347. animation = requestAnimationFrame(update);
  348. } else {
  349. var nodes = document.querySelectorAll(settings[1] ? "IFRAME, EMBED, OBJECT" : "IFRAME");
  350. for(var i = 0; i < nodes.length; i++)
  351. createLazyVideo(nodes[i]);
  352. animation = null;
  353. }
  354. };
  355. update();
  356. })();

QingJ © 2025

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