import { CSSProperties } from "react"; import { sleep } from "."; /** * 動態創建iframe * @param parent 容器節點 * @param url 遊戲網址 * @param style CSSProperties */ export function createIframe(parent: string, url: string, style?: CSSProperties): HTMLIFrameElement { const iframe: HTMLIFrameElement = document.createElement("iframe"); iframe.src = url; iframe.frameBorder = "0"; iframe.scrolling = "0"; for (let i: number = 0, keys: string[] = Object.keys(style); i < keys.length; i++) { const key: string = keys[i]; iframe.style[key] = style[key]; } document.getElementById(parent).appendChild(iframe); return iframe; } /** * 銷毀 iframe * @param parent 容器節點 */ export async function destroyIframe(parent: string) { const iframeContent: HTMLElement = document.getElementById(parent); for (let i = 0; i < iframeContent.children.length; i++) { const iframeNode: HTMLIFrameElement = iframeContent.children[i] as HTMLIFrameElement; try { iframeNode.src = "about:blank"; await sleep(10); const iframeWindow = iframeNode.contentWindow; iframeWindow.document.open(); iframeWindow.document.write(""); iframeWindow.document.clear && iframeWindow.document.clear(); iframeWindow.document.close(); } catch (error) { console.warn(error); } iframeNode.remove(); iframeNode.parentNode && iframeContent.removeChild(iframeNode); // Cocos.CocosEventListener.RemoveAllCallbacks(); // await sleep(2000); } }