-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2386142
commit 278f754
Showing
1 changed file
with
23 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |