Greasy Fork is available in English.

API for CustomElements in YouTube

A JavaScript tool to modify CustomElements in YouTube

このスクリプトは単体で利用できません。右のようなメタデータを含むスクリプトから、ライブラリとして読み込まれます: // @require https://update.greasyfork.org/scripts/465819/1304833/API%20for%20CustomElements%20in%20YouTube.js

このスクリプトの質問や評価の投稿はこちら通報はこちらへお寄せください。
  1. // ==UserScript==
  2. // @name API for CustomElements in YouTube
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.5.3
  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. var customYtElements = (function () {
  38. 'use strict';
  39.  
  40. const injectorCreationForRegistered = ((fnHandler) => {
  41. let mMapOfFuncs = new WeakMap();
  42. if (!(mMapOfFuncs instanceof WeakMap) || (typeof fnHandler !== 'function')) return console.error('[ytI] Incorrect parameters');
  43. const $callee = function (...args) {
  44.  
  45. const f = fnHandler;
  46. if (!f) return console.error('[ytI] the injector is already destroyed.');
  47.  
  48. const isControllerExtraction = typeof this.forwardMethods === 'function' && typeof this._registered === 'undefined';
  49. const isComponentRegister = typeof this._registered === 'function' && typeof this.forwardMethods === 'undefined';
  50. const isSinkWrapper = typeof this.createElement === 'function' && typeof this._registered === 'undefined' && typeof this.forwardMethods === 'undefined';
  51. let warning = '';
  52.  
  53. const map = mMapOfFuncs;
  54. // CE prototype has not yet been "Object.defineProperties()"
  55. const res = f.call(this, ...args); // normally shall be undefined with no arguments
  56. // CE prototype has been "Object.defineProperties()"
  57. // "polymerController" has been added to "this".
  58.  
  59. let polymerController = this.polymerController || this.inst || false;
  60. if (isControllerExtraction) {
  61. if (typeof polymerController !== 'object') {
  62. warning += '[ytI] Controller Extraction is enabled but the corresponding instance is not found.\n';
  63. }
  64. } else if (isComponentRegister || isSinkWrapper) {
  65. //
  66. } else {
  67. warning += "[ytI] customYtElement's definition is undefined.\n";
  68. }
  69. const fnTag = f.__ytHandlerFuncName__;
  70. if (isControllerExtraction && fnTag !== 'forwardMethods') {
  71. warning += "[ytI] Unknown Error in injectorCreationForRegistered. (0x3F01)\n";
  72. }
  73. if (isComponentRegister && fnTag !== '_registered') {
  74. warning += "[ytI] Unknown Error in injectorCreationForRegistered. (0x3F02)\n";
  75. }
  76. if (isSinkWrapper && fnTag !== 'createElement') {
  77. warning += "[ytI] Unknown Error in injectorCreationForRegistered. (0x3F03)\n";
  78. }
  79. let funcs = null;
  80. try {
  81. if (warning) throw warning.trim();
  82. const constructor = this.constructor || null;
  83. if (!constructor || !constructor.prototype) throw '[ytI] CE constructor is not found or invalid.';
  84. // constructor.prototype.${fnTag} = f; // restore to original
  85. delete constructor.prototype[fnTag];
  86. if (constructor.prototype[fnTag] !== f) {
  87. constructor.prototype[fnTag] = f;
  88. }
  89. funcs = map.get(constructor) || 0;
  90. if (typeof funcs.length !== 'number') throw '[ytI] This injection function call is invalid.';
  91. console.debug(`[ytI] ${constructor.prototype.is}'s ${fnTag} has been called.`);
  92. map.set(constructor, null); // invalidate
  93. const proto = polymerController ? polymerController.constructor.prototype : constructor.prototype;
  94. for (const func of funcs) {
  95. func(proto); // developers might implement Promise, setTimeout, or requestAnimation inside the `func`.
  96. }
  97. } catch (e) {
  98. console.warn(e);
  99. } finally {
  100. if (funcs) funcs.length = 0;
  101. }
  102. return res;
  103. }
  104. $callee.__ytHandlerFuncName__ = fnHandler.__ytHandlerFuncName__;
  105. $callee.getMap = () => mMapOfFuncs; // for external
  106. $callee.getOriginalFunction = () => fnHandler; // for external
  107. $callee.destroyObject = function () {
  108. // in addition to GC
  109. mMapOfFuncs = null; // WeakMap does not require clear()
  110. fnHandler = null;
  111. this.__injector__ = null;
  112. this.getMap = null;
  113. this.getOriginalFunction = null;
  114. this.destroyObject = null;
  115. }
  116. // after all injected ${fnHandler} are called,
  117. // customElements.get('ytd-watch-flexy').prototype.${fnHandler}.__injector__.deref() will become undefined.
  118. const wrapped = typeof WeakRef === 'function' ? new WeakRef($callee) : $callee;
  119. $callee.__injector__ = wrapped; // for ${fnHandler}.__injector__
  120. return $callee;
  121. });
  122.  
  123. const injectionPool = (ceProto, fnTag, actionFn) => { // delay prototype injection
  124. if (!(fnTag in ceProto)) return console.warn(`[ytI] no ${fnTag} is found in proto`);
  125. const fnHandler = ceProto[fnTag]; // make a copy in this nested closure.
  126. if (typeof fnHandler !== 'function') return console.warn(`[ytI] proto.${fnTag} is not a function`);
  127. let injector = null;
  128. if (injector = fnHandler.__injector__) {
  129. if (injector.deref) injector = injector.deref(); // null if ${fnTag} of all CEs are restored.
  130. }
  131. if (typeof fnHandler.__ytHandlerFuncName__ === 'string' && fnHandler.__ytHandlerFuncName__ !== fnTag) {
  132. return console.warn(`[ytI] Injection Function Tag Mismatched: ${fnHandler.__ytHandlerFuncName__} & ${fnTag}`);
  133. }
  134. if (!injector) {
  135. fnHandler.__ytHandlerFuncName__ = fnTag;
  136. injector = injectorCreationForRegistered(fnHandler);
  137. // injector.__ytHandlerFuncName__ = fnTag;
  138. fnHandler.__injector__ = injector.__injector__;
  139. } else if (typeof injector.__ytHandlerFuncName__ === 'string' && injector.__ytHandlerFuncName__ !== fnTag) {
  140. return console.warn(`[ytI] Injected Function Tag Mismatched: ${injector.__ytHandlerFuncName__} & ${fnTag}`);
  141. }
  142. if (typeof (injector || 0).getMap !== 'function') return console.warn('[ytI] the injector function is invalid.');
  143. const mapOfFuncs = injector.getMap();
  144. const ceConstructor = ceProto.constructor || null;
  145. if (!ceConstructor) return console.warn('[ytI] no constructor is found in proto');
  146. let funcs;
  147. if (!mapOfFuncs.has(ceConstructor)) {
  148. mapOfFuncs.set(ceConstructor, funcs = []);
  149. ceProto[fnTag] = injector;
  150. } else {
  151. funcs = mapOfFuncs.get(ceConstructor);
  152. }
  153. if (!funcs) return console.warn(`[ytI] ${fnTag} has already called. You can just override the properties.`);
  154. funcs.push(actionFn);
  155. }
  156.  
  157. const postRegistered = (ytElmTag, f) => {
  158. const ceElmConstrcutor = customElements.get(ytElmTag);
  159. const proto = ((ceElmConstrcutor || 0).prototype || 0);
  160.  
  161. let method = 0;
  162.  
  163. if (proto && ('forwardMethods' in proto) && !('_registered' in proto)) {
  164. method = 'forwardMethods';
  165. } else if (proto && ('__hasRegisterFinished' in proto)) {
  166. f(proto);
  167. } else if (proto && ('_registered' in proto) && !('forwardMethods' in proto) && !('createElement' in proto)) {
  168. injectionPool(proto, '_registered', f);
  169. } else if (proto && ('createElement' in proto) && !('_registered' in proto) && !('forwardMethods' in proto)) { // polymer_enable_sink_wrapper = true
  170. method = 'createElement';
  171. } else {
  172. method = -1;
  173. }
  174.  
  175. if (typeof method === 'string') {
  176. // under controller extraction, the register mechanism is different
  177. // register is not done in first initialization
  178. const createdElement = document.querySelector(ytElmTag) || 0;
  179. const polymerController = createdElement.polymerController || createdElement.inst || false;
  180. if (typeof polymerController === 'object') {
  181. f(polymerController.constructor.prototype);
  182. } else {
  183. injectionPool(proto, method, f);
  184. }
  185. } else if (method < 0) {
  186. console.warn('[ytI] postRegistered is not supported.');
  187. }
  188.  
  189. }
  190.  
  191. const EVENT_KEY_ON_REGISTRY_READY = "ytI-ce-registry-created";
  192.  
  193. const customYtElements = {
  194. whenRegistered(ytElmTag, immediateCallback) {
  195. return new Promise(resolve => {
  196. if (typeof customElements !== 'object' || typeof (customElements || 0).whenDefined !== 'function' || typeof customElements.get !== 'function') console.error('[ytI] customElements (native or polyfill) is not available.');
  197. const ceReady = () => { // ignore async result; the result in whenDefined is not the same as customElements.get
  198. postRegistered(ytElmTag, (proto) => {
  199. if (immediateCallback) immediateCallback(proto);
  200. resolve(proto);
  201. });
  202. }
  203. customElements.get(ytElmTag) ? ceReady() : customElements.whenDefined(ytElmTag).then(ceReady);
  204. });
  205. },
  206. onRegistryReady(callback) {
  207. if (typeof customElements === 'undefined') {
  208. if (!('__CE_registry' in document)) {
  209. // https://github.com/webcomponents/polyfills/
  210. Object.defineProperty(document, '__CE_registry', {
  211. get() {
  212. // return undefined
  213. },
  214. set(nv) {
  215. if (typeof nv == 'object') {
  216. delete this.__CE_registry;
  217. this.__CE_registry = nv;
  218. this.dispatchEvent(new CustomEvent(EVENT_KEY_ON_REGISTRY_READY));
  219. }
  220. return true;
  221. },
  222. enumerable: false,
  223. configurable: true
  224. })
  225. }
  226. let eventHandler = (evt) => {
  227. document.removeEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  228. const f = callback;
  229. callback = null;
  230. eventHandler = null;
  231. f();
  232. };
  233. document.addEventListener(EVENT_KEY_ON_REGISTRY_READY, eventHandler, false);
  234. } else {
  235. callback();
  236. }
  237. }
  238. }
  239.  
  240. // Export to external environment
  241. // try { window.customYtElements = customYtElements; } catch (error) { /* for Greasemonkey */ }
  242. // try { module.customYtElements = customYtElements; } catch (error) { /* for CommonJS */ }
  243.  
  244. return customYtElements;
  245.  
  246. })();