fix(stage): iframe 未就绪时跳过注入 magic,避免 contentWindow 为空报错

This commit is contained in:
roymondchen 2026-10-19 17:08:02 +08:00
parent cbd0442ffc
commit d017f43573
2 changed files with 22 additions and 1 deletions

View File

@ -194,7 +194,10 @@ export default class StageRender extends EventEmitter {
}
public postTmagicRuntimeReady() {
this.contentWindow = this.iframe?.contentWindow as RuntimeWindow;
this.contentWindow = (this.iframe?.contentWindow as RuntimeWindow | null) ?? null;
// iframe 尚未就绪时 contentWindow 为空,等 load 后再注入 magic
if (!this.contentWindow) return;
this.contentWindow.magic = this.getMagicApi();

View File

@ -154,6 +154,24 @@ describe('StageRender - NATIVE', () => {
renderer.destroy();
});
test('contentWindow 未就绪时 mount 不抛错,就绪后注入 magic', async () => {
const host = globalThis.document.createElement('div');
globalThis.document.body.appendChild(host);
const renderer = new StageRender({ renderType: RenderType.IFRAME, runtimeUrl: '' });
await expect(renderer.mount(host)).resolves.toBeUndefined();
expect(renderer.contentWindow).toBeNull();
const postMessage = vi.fn();
Object.defineProperty(renderer.iframe!, 'contentWindow', {
configurable: true,
value: { postMessage, document: globalThis.document },
});
renderer.postTmagicRuntimeReady();
expect(postMessage).toHaveBeenCalledWith({ tmagicRuntimeReady: true }, '*');
expect(renderer.contentWindow?.magic).toBeDefined();
renderer.destroy();
});
test('IFRAME getElementsFromPoint 考虑 iframe 偏移', async () => {
const host = globalThis.document.createElement('div');
globalThis.document.body.appendChild(host);