Unhold YouTube Resource Locks

释放 YouTube 用过的 IndexDBs 并禁用 WebLock 让后台页面能进入休眠

  1. /*
  2.  
  3. MIT License
  4.  
  5. Copyright 2022 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 Unhold YouTube Resource Locks
  28. // @name:en Unhold YouTube Resource Locks
  29. // @name:ja Unhold YouTube Resource Locks
  30. // @name:zh-TW Unhold YouTube Resource Locks
  31. // @name:zh-CN Unhold YouTube Resource Locks
  32. // @namespace http://tampermonkey.net/
  33. // @version 2024.03.27.0
  34. // @license MIT License
  35. // @description Release YouTube's used IndexDBs & Disable WebLock to make background tabs able to sleep
  36. // @description:en Release YouTube's used IndexDBs & Disable WebLock to make background tabs able to sleep
  37. // @description:ja YouTube の 使用済みIndexDB を解放し、WebLock を無効にして、バックグラウンドページを休止状態になるように
  38. // @description:zh-TW 釋放 YouTube 用過的 IndexDBs 並禁用 WebLock 讓後台頁面能進入休眠
  39. // @description:zh-CN 释放 YouTube 用过的 IndexDBs 并禁用 WebLock 让后台页面能进入休眠
  40. // @author CY Fung
  41. // @match https://www.youtube.com/*
  42. // @match https://www.youtube.com/embed/*
  43. // @match https://www.youtube-nocookie.com/embed/*
  44. // @exclude https://www.youtube.com/live_chat*
  45. // @exclude https://www.youtube.com/live_chat_replay*
  46. // @match https://music.youtube.com/*
  47. // @match https://m.youtube.com/*
  48. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  49. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/youtube-unlock-indexedDB.png
  50. // @supportURL https://github.com/cyfung1031/userscript-supports
  51.  
  52. // @compatible edge
  53. // @compatible chrome
  54. // @compatible firefox
  55. // @compatible opera
  56.  
  57. // @run-at document-start
  58. // @grant none
  59. // @unwrap
  60. // @allFrames true
  61. // @inject-into page
  62. // ==/UserScript==
  63.  
  64. /* jshint esversion:8 */
  65.  
  66. (function (__window__) {
  67. 'use strict';
  68.  
  69. /** @type {globalThis.PromiseConstructor} */
  70. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  71.  
  72. const DEBUG_LOG = false;
  73. const store = []
  74. let cidxx = 0;
  75. const dbSet = new Set();
  76.  
  77.  
  78. /** @type {(o: Object | null) => WeakRef | null} */
  79. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null); // typeof InvalidVar == 'undefined'
  80.  
  81. /** @type {(wr: Object | null) => Object | null} */
  82. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  83.  
  84.  
  85. const isSupported = (function (console, consoleX) {
  86. 'use strict';
  87. let ww;
  88. try {
  89. ww = new Function('return [window];')()[0]; // real window object
  90. } catch (e) { }
  91.  
  92. const window = ww || __window__;
  93.  
  94. if (typeof (((window || 0).navigator || 0).locks || 0).request === 'function') {
  95. // disable WebLock
  96. // WebLock is just an experimental feature and not really required for YouTube
  97. window.navigator.locks.query = function () {
  98. console.log(arguments);
  99. return new Promise(resolve => {
  100. // do nothing
  101. });
  102. };
  103. window.navigator.locks.request = function () {
  104. console.log(arguments);
  105. return new Promise(resolve => {
  106. // do nothing
  107. });
  108. };
  109. }
  110.  
  111. const isSupported = (((window || 0).indexedDB || 0).constructor || 0).name === 'IDBFactory';
  112. if (isSupported) {
  113. const addEventListenerKey = Symbol();
  114. const removeEventListenerKey = Symbol();
  115. const openKey = Symbol();
  116. const funcHooks = new WeakMap();
  117. let openCount = 0;
  118.  
  119. const msgStore = [];
  120. let messageDisplayCId = 0;
  121. const message = (message) => {
  122. msgStore.push(message);
  123. };
  124. async function releaseOnIdleHandler() {
  125. // console.log('OCK1', openCount, store.length);
  126. if (!cidxx) return
  127. cidxx = 0
  128. DEBUG_LOG && console.log('CLEANING - 01 - BEGIN', openCount);
  129. for (const request of [...dbSet.values()]) {
  130.  
  131. try {
  132. let db = request.result;
  133. let databaseId = db.name
  134. DEBUG_LOG && console.log(db, databaseId);
  135. db.close();
  136. db = null;
  137. openCount--;
  138. message({ databaseId: databaseId, action: 'close', time: Date.now() });
  139.  
  140. } catch (e) { }
  141.  
  142. // releaseOnIdle(target.result, databaseId, eventType, event.type); // start waiting after success / failed of the first lock
  143.  
  144.  
  145. }
  146. dbSet.clear()
  147. DEBUG_LOG && console.log('CLEANING - 01 - END', openCount);
  148.  
  149. DEBUG_LOG && console.log('CLEANING - 02 - BEGIN', openCount);
  150. for (const entry of store) {
  151. let [kdb, databaseId, eventType, event_type] = entry
  152. entry.length = 0
  153. let db = kRef(kdb)
  154. kdb = null
  155.  
  156. DEBUG_LOG && console.log(db, databaseId, eventType, event_type);
  157. db.close();
  158. db = null;
  159. openCount--;
  160. // consoleX.log(openCount, databaseId)
  161. message({ databaseId: databaseId, action: 'close', time: Date.now() });
  162.  
  163. }
  164. store.length = 0
  165. // console.log('OCK2', openCount)
  166.  
  167. DEBUG_LOG && console.log('CLEANING - 02 - END', openCount);
  168.  
  169.  
  170. if (openCount === 0 && msgStore.length > 0) {
  171. if (messageDisplayCId > 0) {
  172. clearTimeout(messageDisplayCId);
  173. messageDisplayCId = 0;
  174. }
  175. messageDisplayCId = setTimeout(() => {
  176. messageDisplayCId = 0;
  177. if (openCount === 0 && msgStore.length > 0) {
  178. let messages = [...msgStore];
  179. msgStore.length = 0;
  180. messages.sort((a, b) => a.databaseId.localeCompare(b.databaseId) || a.time - b.time);
  181. consoleX.dir(messages)
  182. }
  183. }, 300);
  184. }
  185.  
  186.  
  187.  
  188. }
  189. function releaseOnIdle(db, databaseId, eventType, event_type) {
  190. if (cidxx > 0) clearTimeout(cidxx);
  191. store.push([mWeakRef(db), databaseId, eventType, event_type])
  192. // console.log('OC', openCount)
  193. cidxx = setTimeout(releaseOnIdleHandler, 18 * 1000)
  194. }
  195.  
  196. function makeHandler(handler, databaseId, eventType) {
  197. return function (event) {
  198. DEBUG_LOG && console.log(32, 'addEventListener', databaseId, eventType, event.type);
  199. handler.call(this, arguments);
  200. const target = (event || 0).target;
  201. const didNotRemove = dbSet.delete(target);
  202. if (didNotRemove) {
  203. releaseOnIdle(target.result, databaseId, eventType, event.type); // start waiting after success / failed of the first lock
  204. console.log('releaseOnIdle', store.length, databaseId);
  205. }
  206. // dbSet.add()
  207. DEBUG_LOG && console.log(441, 'addEventListener', databaseId, eventType, event.type);
  208. }
  209. }
  210.  
  211. function makeAddEventListener(databaseId) {
  212. DEBUG_LOG && console.log('makeAddEventListener1', databaseId)
  213. return function (eventType, handler) {
  214. DEBUG_LOG && console.log('makeAddEventListener2', databaseId)
  215. if (arguments.length === 2 && eventType === 'error' || eventType === 'success') {
  216. DEBUG_LOG && console.log(31, databaseId, eventType);
  217. let gx = funcHooks.get(handler);
  218. if (!gx) {
  219. gx = makeHandler(handler, databaseId, eventType); // databaseId and eventType are just for logging; not reliable
  220. funcHooks.set(handler, gx);
  221. }
  222. return this[addEventListenerKey](eventType, gx);
  223. }
  224. return this[addEventListenerKey](...arguments);
  225. }
  226. }
  227.  
  228. function makeRemoveEventListener(databaseId) {
  229. return function (eventType, handler) {
  230. if (arguments.length === 2 && eventType === 'error' || eventType === 'success') {
  231. const gx = funcHooks.get(handler);
  232. DEBUG_LOG && console.log(30, 'removeEventListener', databaseId, eventType);
  233. const ret = this[removeEventListenerKey](eventType, gx || handler);
  234. DEBUG_LOG && console.log(442, 'removeEventListener', databaseId, eventType);
  235. return ret;
  236. }
  237. return this[removeEventListenerKey](...arguments);
  238. }
  239. }
  240.  
  241. function makeOpen() {
  242. return function (databaseId) {
  243. const request = this[openKey](databaseId); // IDBRequest
  244. request[addEventListenerKey] = request.addEventListener;
  245. request.addEventListener = makeAddEventListener(databaseId);
  246. request[removeEventListenerKey] = request.removeEventListener;
  247. request.removeEventListener = makeRemoveEventListener(databaseId);
  248. openCount++;
  249. dbSet.add(request);
  250. // console.log('openCount', openCount, databaseId)
  251. if (cidxx > 0) clearTimeout(cidxx);
  252. cidxx = setTimeout(releaseOnIdleHandler, 18 * 1000);
  253. // consoleX.log('opened', openCount, databaseId)
  254. message({ databaseId: databaseId, action: 'open', time: Date.now() });
  255. return request;
  256. }
  257. }
  258. window.indexedDB.constructor.prototype[openKey] = window.indexedDB.constructor.prototype.open;
  259. window.indexedDB.constructor.prototype.open = makeOpen();
  260.  
  261. }
  262. // console.log(22)
  263.  
  264. return isSupported
  265.  
  266. })(DEBUG_LOG ? console : Object.assign({}, console, { log: function () { } }), console);
  267.  
  268.  
  269. })(this instanceof Window ? this : self instanceof Window ? self : window);