API for CustomElements in YouTube

A JavaScript tool to modify CustomElements in YouTube

当前为 2023-05-09 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/465819/1187817/API%20for%20CustomElements%20in%20YouTube.js

  1. // ==UserScript==
  2. // @name API for CustomElements in YouTube
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description A JavaScript tool to modify CustomElements in YouTube
  6. // @author CY Fung
  7. // @grant none
  8. // @license MIT
  9. // ==/UserScript==
  10.  
  11. /*
  12.  
  13. MIT License
  14.  
  15. Copyright (c) 2023 cyfung1031
  16.  
  17. Permission is hereby granted, free of charge, to any person obtaining a copy
  18. of this software and associated documentation files (the "Software"), to deal
  19. in the Software without restriction, including without limitation the rights
  20. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  21. copies of the Software, and to permit persons to whom the Software is
  22. furnished to do so, subject to the following conditions:
  23.  
  24. The above copyright notice and this permission notice shall be included in all
  25. copies or substantial portions of the Software.
  26.  
  27. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  28. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  30. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  32. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  33. SOFTWARE.
  34.  
  35. */
  36.  
  37. const customYtElements = (function () {
  38. 'use strict';
  39.  
  40. const postRegistered = (ytElmTag, f) => {
  41. const ceElmConstrcutor = customElements.get(ytElmTag);
  42. const proto = ((ceElmConstrcutor || 0).prototype || 0);
  43. if (proto && ('__hasRegisterFinished' in proto)) {
  44. f(proto);
  45. } else if (proto && ('_registered' in proto)) {
  46. postRegistered_(proto).push(f);
  47. } else {
  48. console.warn('[tyt] postRegistered is not supported.');
  49. }
  50. }
  51.  
  52. const injectorCreationForRegistered = ((mMapOfFuncs, _registered) => {
  53. if (!(mMapOfFuncs instanceof WeakMap) || (typeof _registered !== 'function')) return console.error('[ytI] Incorrect parameters');
  54. const $callee = function (...args) {
  55. const map = mMapOfFuncs;
  56. const f = _registered;
  57. if (!f) return console.error('[ytI] the injector is already destroyed.');
  58. // CE prototype have not yet been "Object.defineProperties()"
  59. let res = f.call(this, ...args); // normally shall be undefined with no arguments
  60. // CE prototype have been "Object.defineProperties()"
  61. let funcs = null;
  62. try {
  63. const constructor = this.constructor || null;
  64. if (!constructor || !constructor.prototype) throw '[ytI] CE constructor is not found or invalid.';
  65. // constructor.prototype._registered = f; // restore to original
  66. delete constructor.prototype._registered;
  67. if (constructor.prototype._registered !== f) {
  68. constructor.prototype._registered = f;
  69. }
  70. funcs = map.get(constructor) || 0;
  71. if (typeof funcs.length !== 'number') throw '[ytI] This injection function call is invalid.';
  72. console.debug(`[ytI] ${constructor.prototype.is}'s _registered have been called.`);
  73. map.set(constructor, null); // invalidate
  74. for (const func of funcs) {
  75. func(constructor.prototype); // developers might implement Promise, setTimeout, or requestAnimation inside the `func`.
  76. }
  77. } catch (e) {
  78. console.warn(e);
  79. } finally {
  80. if (funcs) funcs.length = 0;
  81. }
  82. return res;
  83. }
  84. $callee.getMap = () => mMapOfFuncs; // for external
  85. $callee.getOriginalFunction = () => _registered; // for external
  86. $callee.destroyObject = function () {
  87. // in addition to GC
  88. mMapOfFuncs = null; // WeakMap does not require clear()
  89. _registered = null;
  90. this.__injector__ = null;
  91. this.getMap = null;
  92. this.getOriginalFunction = null;
  93. this.destroyObject = null;
  94. }
  95. // after all injected _registered are called,
  96. // customElements.get('ytd-watch-flexy').prototype._registered.__injector__.deref() will become undefined.
  97. const wrapped = typeof WeakRef === 'function' ? new WeakRef($callee) : $callee;
  98. $callee.__injector__ = wrapped; // for _registered.__injector__
  99. return $callee;
  100. });
  101.  
  102. const customYtElements = {
  103. whenRegistered(ytElmTag, immediateCallback) {
  104. return new Promise(resolve => {
  105. if (typeof customElements !== 'object' || typeof customElements.whenDefined !== 'function' || typeof customElements.get !== 'function') console.error('[ytI] customElements (native or polyfill) is not available.');
  106. const ceReady = () => { // ignore async result; the result in whenDefined is not the same as customElements.get
  107. postRegistered(ytElmTag, (proto) => {
  108. if (immediateCallback) immediateCallback(proto);
  109. resolve(proto);
  110. });
  111. }
  112. customElements.get(ytElmTag) ? ceReady() : customElements.whenDefined(ytElmTag).then(ceReady);
  113. });
  114. }
  115. }
  116.  
  117. const postRegistered_ = (ceProto) => { // delay prototype injection
  118. if (!('_registered' in ceProto)) return console.warn('[ytI] no _registered is found in proto');
  119. const _registered = ceProto._registered; // make a copy in this nested closure.
  120. if (typeof _registered !== 'function') return console.warn('[ytI] proto._registered is not a function');
  121. let injector = null;
  122. if (injector = _registered.__injector__) {
  123. if (injector.deref) injector = injector.deref(); // null if _registered of all CEs are restored.
  124. }
  125. if (!injector) {
  126. injector = injectorCreationForRegistered(new WeakMap(), _registered);
  127. _registered.__injector__ = injector.__injector__;
  128. }
  129. if (typeof (injector || 0).getMap !== 'function') return console.warn('[ytI] the injector function is invalid.');
  130. const mapOfFuncs = injector.getMap();
  131. const ceConstructor = ceProto.constructor || null;
  132. if (!ceConstructor) return console.warn('[ytI] no constructor is found in proto');
  133. let funcs;
  134. if (!mapOfFuncs.has(ceConstructor)) {
  135. mapOfFuncs.set(ceConstructor, funcs = []);
  136. ceProto._registered = injector;
  137. } else {
  138. funcs = mapOfFuncs.get(ceConstructor);
  139. }
  140. if (!funcs) return console.warn('[ytI] _registered has already called. You can just override the properties.');
  141. return funcs;
  142. }
  143. // Export to external environment
  144. try { window.customYtElements = customYtElements; } catch (error) { /* for Greasemonkey */ }
  145. try { module.customYtElements = customYtElements; } catch (error) { /* for CommonJS */ }
  146. return customYtElements;
  147.  
  148. })();