/** 跨上下文快速调用 */ export class Calls { idpool = 0 callMap: any = {} onMap: any = {} constructor(public target: any) { target.addEventListener( "message", async (e: any) => { if (e.data.__isResult) { let resolve = this.callMap[e.data.__callId] resolve(e.data.__re) } else { let method = e.data.method let onFunc = this.onMap[method] if (onFunc) { let re try { re = await onFunc(e.data.data) } catch (e) { re = { error: e } } let id = e.data.__callId this.target.postMessage({ __re: re, __isResult: true, __callId: id }) } } }, false ) } async post(method: string, data: any, transferable?: any): Promise { let id = this.idpool++ let payload = Object.assign({}, { data, method, __callId: id }) this.target.postMessage(payload, transferable) return new Promise((resolve, reject) => { this.callMap[id] = resolve }) } async on(method: string, func: (data: any) => any) { this.onMap[method] = func } }