YouTube CPU Tamer by AnimationFrame

减少YouTube影片所致的能源消耗

目前为 2024-03-04 提交的版本。查看 最新版本

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2021-2023 CY Fung
  6.  
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13.  
  14. The above copyright notice and this permission notice shall be included in all
  15. copies or substantial portions of the Software.
  16.  
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24.  
  25. */
  26. // ==UserScript==
  27. // @name YouTube CPU Tamer by AnimationFrame
  28. // @name:ja YouTube CPU Tamer by AnimationFrame
  29. // @name:zh-TW YouTube CPU Tamer by AnimationFrame
  30. // @namespace http://tampermonkey.net/
  31. // @version 2024.03.04.2
  32. // @license MIT License
  33. // @author CY Fung
  34. // @match https://www.youtube.com/*
  35. // @match https://www.youtube.com/embed/*
  36. // @match https://www.youtube-nocookie.com/embed/*
  37. // @match https://www.youtube.com/live_chat*
  38. // @match https://www.youtube.com/live_chat_replay*
  39. // @match https://music.youtube.com/*
  40. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  41. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/youtube-cpu-tamper-by-animationframe.webp
  42. // @supportURL https://github.com/cyfung1031/userscript-supports
  43. // @run-at document-start
  44. // @grant none
  45. // @unwrap
  46. // @allFrames true
  47. // @inject-into page
  48.  
  49. // @description Reduce Browser's Energy Impact for playing YouTube Video
  50. // @description:en Reduce Browser's Energy Impact for playing YouTube Video
  51. // @description:ja YouTubeビデオのエネルギーインパクトを減らす
  52. // @description:zh-TW 減少YouTube影片所致的能源消耗
  53. // @description:zh-CN 减少YouTube影片所致的能源消耗
  54.  
  55. // @description:ko YouTube 비디오 재생 시 브라우저의 에너지 영향을 줄입니다.
  56. // @description:ru Снижает энергетическое воздействие браузера при воспроизведении видео на YouTube.
  57. // @description:af Verminder die energie-impak van die blaaier vir YouTube-video speel
  58. // @description:az YouTube videolarını oynamaq üçün Brauzer enerji təsirini azaldır
  59. // @description:id Kurangi Dampak Energi Browser untuk memutar Video YouTube
  60. // @description:ms Kurangkan Impak Tenaga Pelayar untuk memainkan Video YouTube
  61. // @description:bs Smanji energetski uticaj preglednika za reprodukciju YouTube videa
  62. // @description:ca Redueix l'impacte energètic del navegador per reproduir vídeos de YouTube
  63. // @description:cs Snížit energetický dopad prohlížeče při přehrávání videí na YouTube
  64. // @description:da Reducer browserens energipåvirkning for at afspille YouTube-video
  65. // @description:de Reduzieren Sie die Energieauswirkungen des Browsers für die Wiedergabe von YouTube-Videos
  66. // @description:et Vähendage YouTube'i video esitamiseks brauseri energiamõju
  67. // @description:es Reduzca el impacto energético del navegador al reproducir videos de YouTube
  68. // @description:eu Gutxitu nabigatzeko energiaren eragina YouTube bideoak erreproduzitzeko
  69. // @description:fr Réduire l'impact énergétique du navigateur lors de la lecture de vidéos YouTube
  70. // @description:gl Reduzca o impacto enerxético do navegador para reproducir vídeos de YouTube
  71. // @description:hr Smanjite energetski utjecaj preglednika za reprodukciju YouTube videa
  72. // @description:zu Qaqalitsha Umbono We-Energy we-Browser ukuze udlale i-Video ye-YouTube
  73. // @description:is Minkaðu orkuáhrif vafra til að spila YouTube myndband
  74. // @description:it Riduci l'impatto energetico del browser per la riproduzione di video di YouTube
  75. // @description:sw Punguza Athari ya Nishati ya Kivinjari kwa kucheza Video za YouTube
  76. // @description:lv Samaziniet pārlūkprogrammas enerģijas ietekmi YouTube video atskaņošanai
  77. // @description:lt Sumažinkite naršyklės energijos poveikį žaidžiant „YouTube“ vaizdo įrašus
  78. // @description:hu Csökkentse a böngésző energiaterhelését a YouTube videó lejátszásához
  79. // @description:nl Verminder de energie-impact van de browser bij het afspelen van YouTube-video's
  80. // @description:uz YouTube videoni tinglash uchun brauzer energiyasi ta'sirini kamaytirish
  81. // @description:pl Zmniejsz zużycie energii przeglądarki podczas odtwarzania filmów na YouTube
  82. // @description:pt Reduza o Impacto Energético do Navegador ao reproduzir Vídeos do YouTube
  83. // @description:pt-BR Reduza o Impacto Energético do Navegador ao reproduzir Vídeos do YouTube
  84. // @description:ro Reduceți impactul energetic al browser-ului pentru redarea videoclipurilor YouTube
  85. // @description:sq Zvogëlo ndikimin e energjisë të shfletuesit për luajtjen e video YouTube
  86. // @description:sk Znížte energetický dopad prehliadača pri prehrávaní videí na YouTube
  87. // @description:sl Zmanjšajte energijski vpliv brskalnika pri predvajanju videoposnetkov YouTube
  88. // @description:sr Smanjite energetski uticaj pregledača za reprodukciju YouTube videa
  89. // @description:fi Vähennä selaimen energiankulutusta YouTube-videoiden toistossa
  90. // @description:sv Minska webbläsarens energipåverkan för att spela YouTube-video
  91. // @description:vi Giảm tác động năng lượng của trình duyệt khi phát Video YouTube
  92. // @description:tr YouTube Videolarını Oynatırken Tarayıcının Enerji Etkisini Azaltın
  93. // @description:be Змяншыце энергетычны ўплыў браўзара на прайграванне YouTube-відэа
  94. // @description:bg Намалете енергийния влияние на браузъра при възпроизвеждане на видео в YouTube
  95. // @description:ky YouTube видеонун ойнотуусунан башкаруу үчүн браузердеги энергиялык турмуштарды көмүштөштүрүү
  96. // @description:kk YouTube-дың браузерде көрсету мүмкіндігін көмеге қысқартыңыз
  97. // @description:mk Намалете ја енергетската присутност на пребарувачот за репродукција на YouTube видео
  98. // @description:mn YouTube видеогийг тоглуулж буй хөтөчийн энерги хүчинг буурах
  99. // @description:uk Зменште енергетичний вплив браузера на відтворення відео на YouTube
  100. // @description:el Μειώστε την ενεργειακή επίδραση του προγράμματος περιήγησης για την αναπαραγωγή βίντεο στο YouTube
  101. // @description:hy Փոքրանալիքայինը դանդարեցրեք բրաուզերի էներգիայի ազդեցությունը YouTube վիդեոների ներածման դեպքում
  102. // @description:ur یوٹیوب ویڈیو کھیلنے کے لئے براؤزر کی توانائی پر اثر کم کریں
  103. // @description:ar تقليل تأثير استهلاك الطاقة لمتصفح تشغيل مقاطع فيديو يوتيوب
  104. // @description:fa کاهش تأثیر انرژی مرورگر برای پخش ویدئوی یوتیوب
  105. // @description:ne युट्युब भिडियो खेल्नका लागि ब्राउजरको ऊर्जा प्रभाव कम गर्नुहोस्
  106. // @description:mr YouTube व्हिडिओ चालवण्यासाठी ब्राउझरचे ऊर्जाचे प्रभाव कमी करा
  107. // @description:hi यूट्यूब वीडियो चलाने के लिए ब्राउज़र की ऊर्जा प्रभाव को कम करें
  108. // @description:as YouTube ভিডিঅ' প্ৰশ্ন কৰা ব্ৰাউজাৰৰ শক্তিৰ প্ৰভাৱ কমিয়া দিব
  109. // @description:bn YouTube ভিডিও চালাতে ব্রাউজারের শক্তি প্রভাব কমান
  110. // @description:pa YouTube ਵਿਡੀਓ ਚਲਾਉਣ ਲਈ ਬਰਾਉਜ਼ਰ ਦੀ ਊਰਜਾ ਪ੍ਰਭਾਵ ਘਟਾਓ
  111. // @description:gu YouTube વિડિઓ ચલાવવા માટે બ્રાઉઝરનું ઊર્જા પ્રભાવ ઘટાડો
  112. // @description:or YouTube ଭିଡିଓ ଚାଲାନ୍ତୁ ପାଇଁ ବ୍ରାଉଜରର ଶକ୍ତି ପ୍ରଭାବ କମାନ୍ତୁ
  113. // @description:ta யூடியூப் வீடியோவை இயக்குவதற்கான உலாவியின் மிக்க விளைவுகளை குறைக்கவும்
  114. // @description:te YouTube వీడియోను ప్రసారం చేయడానికి బ్రౌజర్ యొక్క శక్తి ప్రభావాన్ని తగ్గించుకోండి
  115. // @description:kn YouTube ವೀಡಿಯೊಗಳನ್ನು ಪ್ರದರ್ಶಿಸಲು ಬ್ರೌಸರ್ ಯನ್ನು ಉಪಯೋಗಿಸುವಾಗ ಶಕ್ತಿ ಪ್ರಭಾವವನ್ನು ಕಡಿಮೆಗೊಳಿಸಿ
  116. // @description:ml YouTube വീഡിയോ പ്രവർത്തിപ്പിക്കുവാൻ ബ്രൗസർയുടെ പ്രഭാവം കുറയ്ക്കുക
  117. // @description:si YouTube වීඩියෝ චාරිකා කිරීම සඳහා බ්‍රවුසරයේ ඊම්ජි බලන්න
  118. // @description:th ลดผลกระทบทางพลังงานของเบราว์เซอร์ในการเล่นวิดีโอ YouTube
  119. // @description:lo ບຣາຣິໂຄດລາວເອີ້ນໃນການເພີ່ມເວັບວຽກຂອງ YouTube ສຳ ລັບການຂະໜາດໃນການເພີ່ມເວັບວຽກ
  120. // @description:my YouTube ဗီဒီယိုများကို ဖွင့်ရန် Browser အတွက် Energy Impact ကိုအနိုင်ရန်
  121. // @description:ka YouTube ვიდეოების დაკვრებისას ბრაუზერის ენერგიის შეცვლა
  122. // @description:am YouTube ቪዲዮዎችን ለመቀነስ የባህሪውን አርእስት ግንኙነት ማድረግ
  123. // @description:km បង្កើតការធ្វើបរិមាណលំអិតរបស់ការកំណត់ការដាក់នៅលើសម្ពាធរបស់ប្រព័ន្ធបញ្ចូលបន្ទាត់ YouTube
  124. // ==/UserScript==
  125.  
  126. /* jshint esversion:8 */
  127.  
  128. ((__CONTEXT__) => {
  129. 'use strict';
  130.  
  131. const win = this instanceof Window ? this : window;
  132.  
  133. // Create a unique key for the script and check if it is already running
  134. const hkey_script = 'nzsxclvflluv';
  135. if (win[hkey_script]) throw new Error('Duplicated Userscript Calling'); // avoid duplicated scripting
  136. win[hkey_script] = true;
  137.  
  138. /** @type {globalThis.PromiseConstructor} */
  139. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  140. const PromiseExternal = ((resolve_, reject_) => {
  141. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  142. return class PromiseExternal extends Promise {
  143. constructor(cb = h) {
  144. super(cb);
  145. if (cb === h) {
  146. /** @type {(value: any) => void} */
  147. this.resolve = resolve_;
  148. /** @type {(reason?: any) => void} */
  149. this.reject = reject_;
  150. }
  151. }
  152. };
  153. })();
  154. const cleanContext = async (win) => {
  155. const waitFn = requestAnimationFrame; // shall have been binded to window
  156. try {
  157. let mx = 16; // MAX TRIAL
  158. const frameId = 'vanillajs-iframe-v1'
  159. let frame = document.getElementById(frameId);
  160. let removeIframeFn = null;
  161. if (!frame) {
  162. frame = document.createElement('iframe');
  163. frame.id = frameId;
  164. const blobURL = typeof webkitCancelAnimationFrame === 'function' ? (frame.src = URL.createObjectURL(new Blob([], { type: 'text/html' }))) : null; // avoid Brave Crash
  165. frame.sandbox = 'allow-same-origin'; // script cannot be run inside iframe but API can be obtained from iframe
  166. let n = document.createElement('noscript'); // wrap into NOSCRPIT to avoid reflow (layouting)
  167. n.appendChild(frame);
  168. while (!document.documentElement && mx-- > 0) await new Promise(waitFn); // requestAnimationFrame here could get modified by YouTube engine
  169. const root = document.documentElement;
  170. root.appendChild(n); // throw error if root is null due to exceeding MAX TRIAL
  171. if (blobURL) Promise.resolve().then(() => URL.revokeObjectURL(blobURL));
  172.  
  173. removeIframeFn = (setTimeout) => {
  174. const removeIframeOnDocumentReady = (e) => {
  175. e && win.removeEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  176. e = n;
  177. n = win = removeIframeFn = 0;
  178. setTimeout ? setTimeout(() => e.remove(), 200) : e.remove();
  179. }
  180. if (!setTimeout || document.readyState !== 'loading') {
  181. removeIframeOnDocumentReady();
  182. } else {
  183. win.addEventListener("DOMContentLoaded", removeIframeOnDocumentReady, false);
  184. }
  185. }
  186. }
  187. while (!frame.contentWindow && mx-- > 0) await new Promise(waitFn);
  188. const fc = frame.contentWindow;
  189. if (!fc) throw "window is not found."; // throw error if root is null due to exceeding MAX TRIAL
  190. try {
  191. const { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout } = fc;
  192. const res = { requestAnimationFrame, setInterval, setTimeout, clearInterval, clearTimeout };
  193. for (let k in res) res[k] = res[k].bind(win); // necessary
  194. if (removeIframeFn) Promise.resolve(res.setTimeout).then(removeIframeFn);
  195. return res;
  196. } catch (e) {
  197. if (removeIframeFn) removeIframeFn();
  198. return null;
  199. }
  200. } catch (e) {
  201. console.warn(e);
  202. return null;
  203. }
  204. };
  205.  
  206. cleanContext(win).then(__CONTEXT__ => {
  207.  
  208. if (!__CONTEXT__) return null;
  209.  
  210. const { requestAnimationFrame, setTimeout, setInterval, clearTimeout, clearInterval } = __CONTEXT__;
  211.  
  212. /** @type {Function|null} */
  213. let afInterupter = null;
  214.  
  215. const getRAFHelper = () => {
  216. const asc = document.createElement('a-f');
  217. if (!('onanimationiteration' in asc)) {
  218. return (resolve) => requestAnimationFrame(afInterupter = resolve);
  219. }
  220. asc.id = 'a-f';
  221. let qr = null;
  222. asc.onanimationiteration = function () {
  223. if (qr !== null) {
  224. qr();
  225. qr = null;
  226. }
  227. }
  228. const style = document.createElement('style');
  229. style.textContent = `
  230. @keyFrames aF1 {
  231. 0% {
  232. order: 0;
  233. }
  234. 100% {
  235. order: 6;
  236. }
  237. }
  238. #a-f[id] {
  239. visibility: collapse !important;
  240. position: fixed !important;
  241. top: -100px !important;
  242. left: -100px !important;
  243. margin:0 !important;
  244. padding:0 !important;
  245. outline:0 !important;
  246. border:0 !important;
  247. z-index:-1 !important;
  248. width: 0px !important;
  249. height: 0px !important;
  250. contain: strict !important;
  251. pointer-events: none !important;
  252. animation: 1ms steps(2) 0ms infinite alternate forwards running aF1 !important;
  253. }
  254. `;
  255. (document.head || document.documentElement).appendChild(style);
  256. document.documentElement.insertBefore(asc, document.documentElement.firstChild);
  257. return (resolve) => (qr = afInterupter = resolve);
  258. };
  259.  
  260. /** @type {(resolve: () => void)} */
  261. const rafPN = getRAFHelper(); // rAF will not execute if document is hidden
  262.  
  263. (() => {
  264. let afPromiseP, afPromiseQ; // non-null
  265. afPromiseP = afPromiseQ = { resolved: true }; // initial state for !rP && !rQ
  266. let afix = 0;
  267. const afResolve = async (rX) => {
  268. await new Promise(rafPN);
  269. rX.resolved = true;
  270. const t = ++afix;
  271. if (t > 9e9) afix = 9;
  272. return rX.resolve(t), t;
  273. };
  274. const eFunc = async () => {
  275. const uP = !afPromiseP.resolved ? afPromiseP : null;
  276. const uQ = !afPromiseQ.resolved ? afPromiseQ : null;
  277. let t = 0;
  278. if (uP && uQ) {
  279. const t1 = await uP;
  280. const t2 = await uQ;
  281. t = t1 > t2 && t1 - t2 < 8e9 ? t1 : t2;
  282. } else {
  283. const vP = !uP ? (afPromiseP = new PromiseExternal()) : null;
  284. const vQ = !uQ ? (afPromiseQ = new PromiseExternal()) : null;
  285. if (uP) await uP;
  286. else if (uQ) await uQ;
  287. if (vP) t = await afResolve(vP);
  288. if (vQ) t = await afResolve(vQ);
  289. }
  290. return t;
  291. }
  292. const inExec = new Set();
  293. const sFunc = (propFunc) => {
  294. return (func, ms = 0, ...args) => {
  295. if (typeof func === 'function') { // ignore all non-function parameter (e.g. string)
  296. const hasArgs = args.length > 0;
  297. const handler = hasArgs ? func.bind(null, ...args) : func; // original func if no extra argument
  298. let lastExecution = 0;
  299. const cid = propFunc(async () => {
  300. try {
  301. inExec.add(cid);
  302. const t = await eFunc();
  303. if (inExec.has(cid)) {
  304. inExec.delete(cid);
  305. if (t !== lastExecution) {
  306. lastExecution = t;
  307. handler();
  308. }
  309. }
  310. } catch (e) {
  311. console.error(e);
  312. throw e;
  313. }
  314. }, ms);
  315. return cid;
  316. } else {
  317. return propFunc(func, ms, ...args);
  318. }
  319. };
  320. };
  321. win.setTimeout = sFunc(setTimeout);
  322. win.setInterval = sFunc(setInterval);
  323.  
  324. const dFunc = (propFunc) => {
  325. return (cid) => {
  326. if (cid) inExec.has(cid) ? inExec.delete(cid) : propFunc(cid);
  327. };
  328. };
  329.  
  330. win.clearTimeout = dFunc(clearTimeout);
  331. win.clearInterval = dFunc(clearInterval);
  332.  
  333. try {
  334. win.setTimeout.toString = setTimeout.toString.bind(setTimeout)
  335. win.setInterval.toString = setInterval.toString.bind(setInterval)
  336. win.clearTimeout.toString = clearTimeout.toString.bind(clearTimeout)
  337. win.clearInterval.toString = clearInterval.toString.bind(clearInterval)
  338. } catch (e) { console.warn(e) }
  339.  
  340. })();
  341.  
  342. let mInterupter = null;
  343. setInterval(() => {
  344. const dInterupter = afInterupter;
  345. if (dInterupter !== null && mInterupter === dInterupter) {
  346. afInterupter = null;
  347. mInterupter = null;
  348. dInterupter();
  349. } else {
  350. mInterupter = dInterupter;
  351. }
  352. }, 125);
  353. });
  354.  
  355. })(null);

QingJ © 2025

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