Greasy Fork镜像 支持简体中文。

YouTube CPU Tamer by DOMMutation

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

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

QingJ © 2025

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