tanghaolin
2025-04-20 fe4b76e24c82abf35afaaa07f3e681ba14ee2d80
src/utils/iframeCall.ts
@@ -1,43 +1,17 @@
/**
 * 设置全局函数,用于 Child 注册
 */
export const registerChildFunction = () => {
   /** @description 把 Child 的函数注册过来, 方便自己调用 */
   (window as any).register = (cb: (...args: any[]) => void) => {
      console.log('register children function');
      (window as any).childCall = (...args: any[]) => {
         cb?.(...args);
      };
   };
const notifyFunc = (jsonObj: any) => {
   console.log('message from parent🚀 ~ jsonObj:', jsonObj);
   // 执行AI通知消息
};
const fun = (msg: string) => {
   console.log('函数来自parent', msg);
};
/**
 * 往 windows 上加函数,给 child 调用
 */
export const setParentFunction = () => {
   let child: any;
   for (let index = 0; index < window.frames.length; index++) {
      const frame = window.frames[index];
      if ((frame as any).register) {
         child = frame;
         break;
export class ChildRegister {
   static childCallObj = null;
   static registerNotifyFunction() {
      for (let index = 0; index < window.frames.length; index++) {
         const frame = window.frames[index];
         if ((frame as any).registerNotifyFunction) {
            ChildRegister.childCallObj = (frame as any).registerNotifyFunction(notifyFunc);
            break;
         }
      }
   }
   if (!child) return;
   child.register?.(fun);
};
/**
 * 子 iframe 调用
 */
export const childCall = (...args: any[]) => {
   (window as any)?.childCall?.(...args);
};
for (let index = 0; index < window.frames.length; index++) {
   const element = window.frames[index];
   console.log('🚀 ~ element:', element);
}