From 278f754650b85cdc65d41b3e0603b5a0c0f88c41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=A7=E5=8A=A8=E7=89=A9?= <15294745236@163.com> Date: Sun, 25 Aug 2024 19:49:07 +0800 Subject: [PATCH] add utils --- src/utils/postMessage.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/utils/postMessage.ts diff --git a/src/utils/postMessage.ts b/src/utils/postMessage.ts new file mode 100644 index 0000000..ea2805e --- /dev/null +++ b/src/utils/postMessage.ts @@ -0,0 +1,23 @@ +class PostMessage { + #iFrame: HTMLIFrameElement|null =null; + #targetOrigin: string = ''; + constructor(el:HTMLIFrameElement, targetOrigin: string) { + this.#iFrame = el; + this.#targetOrigin = targetOrigin; + window.addEventListener('message',this.handle,false) + } + sendMessage(message: any) { + this.#iFrame!.contentWindow!.postMessage(message,this.#targetOrigin); + } + private handle(e: MessageEvent) { + if(e.origin===this.#targetOrigin){ + console.log(e.origin) //父页面URL,这里是http://a.index.com + console.log(e.source) // 父页面window对象,全等于window.parent/window.top + console.log(e.data) //父页面发送的消息 + } + } + destroy() { + window.removeEventListener('message',this.handle,false) + } +} +export default PostMessage; \ No newline at end of file