|
| 1 | +export function detectIframeApp(target: Window | typeof globalThis, inIframe = false) { |
| 2 | + if (inIframe) { |
| 3 | + function sendEventToParent(cb) { |
| 4 | + try { |
| 5 | + // @ts-expect-error skip type check |
| 6 | + const hook = window.parent.__VUE_DEVTOOLS_GLOBAL_HOOK__ |
| 7 | + if (hook) { |
| 8 | + cb(hook) |
| 9 | + } |
| 10 | + } |
| 11 | + catch (e) { |
| 12 | + // Ignore |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + const hook = { |
| 17 | + id: 'vue-devtools-next', |
| 18 | + devtoolsVersion: '7.0', |
| 19 | + on: (event, cb) => { |
| 20 | + sendEventToParent((hook) => { |
| 21 | + hook.on(event, cb) |
| 22 | + }) |
| 23 | + }, |
| 24 | + once: (event, cb) => { |
| 25 | + sendEventToParent((hook) => { |
| 26 | + hook.once(event, cb) |
| 27 | + }) |
| 28 | + }, |
| 29 | + off: (event, cb) => { |
| 30 | + sendEventToParent((hook) => { |
| 31 | + hook.off(event, cb) |
| 32 | + }) |
| 33 | + }, |
| 34 | + emit: (event, ...payload) => { |
| 35 | + sendEventToParent((hook) => { |
| 36 | + hook.emit(event, ...payload) |
| 37 | + }) |
| 38 | + }, |
| 39 | + } |
| 40 | + |
| 41 | + Object.defineProperty(target, '__VUE_DEVTOOLS_GLOBAL_HOOK__', { |
| 42 | + get() { |
| 43 | + return hook |
| 44 | + }, |
| 45 | + configurable: true, |
| 46 | + }) |
| 47 | + } |
| 48 | + |
| 49 | + function injectVueHookToIframe(iframe) { |
| 50 | + if (iframe.__vdevtools__injected) { |
| 51 | + return |
| 52 | + } |
| 53 | + try { |
| 54 | + iframe.__vdevtools__injected = true |
| 55 | + const inject = () => { |
| 56 | + console.log('inject', iframe) |
| 57 | + try { |
| 58 | + iframe.contentWindow.__VUE_DEVTOOLS_IFRAME__ = iframe |
| 59 | + const script = iframe.contentDocument.createElement('script') |
| 60 | + script.textContent = `;(${detectIframeApp.toString()})(window, true)` |
| 61 | + iframe.contentDocument.documentElement.appendChild(script) |
| 62 | + script.parentNode.removeChild(script) |
| 63 | + } |
| 64 | + catch (e) { |
| 65 | + // Ignore |
| 66 | + } |
| 67 | + } |
| 68 | + inject() |
| 69 | + iframe.addEventListener('load', () => inject()) |
| 70 | + } |
| 71 | + catch (e) { |
| 72 | + // Ignore |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + // detect iframe app to inject vue hook |
| 77 | + function injectVueHookToIframes() { |
| 78 | + if (typeof window === 'undefined') { |
| 79 | + return |
| 80 | + } |
| 81 | + |
| 82 | + const iframes = Array.from(document.querySelectorAll<HTMLIFrameElement>('iframe:not([data-vue-devtools-ignore])')) |
| 83 | + for (const iframe of iframes) { |
| 84 | + injectVueHookToIframe(iframe) |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + injectVueHookToIframes() |
| 89 | + |
| 90 | + let iframeAppChecks = 0 |
| 91 | + const iframeAppCheckTimer = setInterval(() => { |
| 92 | + injectVueHookToIframes() |
| 93 | + iframeAppChecks++ |
| 94 | + if (iframeAppChecks >= 5) { |
| 95 | + clearInterval(iframeAppCheckTimer) |
| 96 | + } |
| 97 | + }, 1000) |
| 98 | +} |
0 commit comments