YouTube CPU Tamer by DOMMutation

YouTube 비디오 재생 시 브라우저의 에너지 영향을 줄입니다.

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