Skip to content

Commit

Permalink
add utils
Browse files Browse the repository at this point in the history
  • Loading branch information
greatanimalion committed Aug 25, 2024
1 parent 2386142 commit 278f754
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/utils/postMessage.ts
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 278f754

Please sign in to comment.