YouTube CPU Tamer by DOMMutation

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

目前為 2025-03-31 提交的版本,檢視 最新版本

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

QingJ © 2025

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