|
| 1 | +/** |
| 2 | + * hijackScript - Intercept script loading |
| 3 | + * @param callback Callback function that receives the script node and can modify or block script execution |
| 4 | + */ |
| 5 | +export function hijackScript(callback: (node: HTMLScriptElement) => void) { |
| 6 | + const dynamicScripts = new WeakSet<HTMLScriptElement>() |
| 7 | + |
| 8 | + const originalCreateElement = document.createElement.bind(document) |
| 9 | + document.createElement = ((tagName: string, options?: any) => { |
| 10 | + const element = originalCreateElement(tagName, options) |
| 11 | + if (tagName.toLowerCase() === 'script') { |
| 12 | + dynamicScripts.add(element as HTMLScriptElement) |
| 13 | + } |
| 14 | + return element |
| 15 | + }) as typeof document.createElement |
| 16 | + |
| 17 | + const originalAppendChild = Node.prototype.appendChild |
| 18 | + Node.prototype.appendChild = function <T extends Node>(node: T): T { |
| 19 | + if (node instanceof HTMLScriptElement && dynamicScripts.has(node)) { |
| 20 | + callback(node) |
| 21 | + } |
| 22 | + return originalAppendChild.call(this, node) as T |
| 23 | + } |
| 24 | + |
| 25 | + const originalInsertBefore = Node.prototype.insertBefore |
| 26 | + Node.prototype.insertBefore = function <T extends Node>(node: T, child: Node | null): T { |
| 27 | + if (node instanceof HTMLScriptElement && dynamicScripts.has(node)) { |
| 28 | + callback(node) |
| 29 | + } |
| 30 | + return originalInsertBefore.call(this, node, child) as T |
| 31 | + } |
| 32 | + |
| 33 | + const observer = new MutationObserver((mutations) => { |
| 34 | + mutations.forEach((mutation) => { |
| 35 | + mutation.addedNodes.forEach((node) => { |
| 36 | + if (node instanceof HTMLScriptElement && !dynamicScripts.has(node)) { |
| 37 | + callback(node) |
| 38 | + } |
| 39 | + }) |
| 40 | + }) |
| 41 | + }) |
| 42 | + |
| 43 | + observer.observe(document.documentElement, { |
| 44 | + childList: true, |
| 45 | + subtree: true, |
| 46 | + }) |
| 47 | + |
| 48 | + return () => { |
| 49 | + document.createElement = originalCreateElement |
| 50 | + Node.prototype.appendChild = originalAppendChild |
| 51 | + Node.prototype.insertBefore = originalInsertBefore |
| 52 | + observer.disconnect() |
| 53 | + } |
| 54 | +} |
0 commit comments