diff --git a/src/utils.ts b/src/utils.ts index 02e339b..1a209e4 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -47,9 +47,29 @@ export const useTimeout = async (promise: T | Promise, ms: number): Promi }) } -export const getSandboxWindowAsync = async (targetEl = document.documentElement): Promise => { +export const getSandboxWindowAsync = async (targetEl: Element | undefined = undefined): Promise => { if (typeof document === 'undefined') return {} as any as Window + if (!targetEl) { + return new Promise((resolve) => { + // You need ads in your pages, right? + const observer = new MutationObserver(() => { + for (let i = 0; i < window.frames.length; i++) { + // find iframe windows created by ads + const frame = frames[i] + try { + const href = frame.location.href + if (href === location.href || href === 'about:blank') { + resolve(frame) + return + } + } catch { } + } + }) + observer.observe(document.body, { subtree: true, childList: true }) + }) + } + return new Promise((resolve) => { const eventName = 'onmousemove' const id = Math.random().toString() @@ -75,7 +95,7 @@ export const getUnsafeWindow = (): Window => { export const console: Console = (window || global).console // Object.is(window.console, unsafeWindow.console) == false -export const windowOpenAsync = (targetEl = document.documentElement, ...args: Parameters): Promise => { +export const windowOpenAsync = (targetEl: Element | undefined, ...args: Parameters): Promise => { return getSandboxWindowAsync(targetEl).then(w => w.open(...args)) }