Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第289天 说说你对postMessage的理解,它有什么运用场景呢? #1838

Open
haizhilin2013 opened this issue Jan 29, 2020 · 3 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第289天 说说你对postMessage的理解,它有什么运用场景呢?

我也要出题

@haizhilin2013 haizhilin2013 added the js JavaScript label Jan 29, 2020
@cxwht
Copy link

cxwht commented Jan 31, 2020

window.postMessage() 方法可以安全地实现跨源通信。通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为https),端口号(443为https的默认值),以及主机 (两个页面的模数 Document.domain设置为相同的值) 时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,只要正确的使用,这种方法就很安全。

从广义上讲,一个窗口可以获得对另一个窗口的引用(比如 targetWindow = window.opener),然后在窗口上调用 targetWindow.postMessage() 方法分发一个 MessageEvent 消息。接收消息的窗口可以根据需要自由处理此事件。传递给 window.postMessage() 的参数(比如 message )将通过消息事件对象暴露给接收消息的窗口。

资料来自 MDN

@xiaoqiangz
Copy link

postMessage 一般是用于对不同的两个iframe页面通信使用,可以实现跨源通信。
可以在某窗口上调用 one.postMessage()方法来派发消息,然后其他窗口可以通过window.addEventListener("message", receiveMessage, false);来监听分发的message

@Wyt-GitHub8000
Copy link

postMessage() 是一种用于在 Web 浏览器中的两个不同窗口或选项卡之间进行通信的方法。它允许在不同页面上运行的脚本相互通信,而不需要它们共享同一个域。

该方法有两个参数,data 和 origin。 data 参数是一个对象,可以包含需要发送到目标窗口的任何信息,而 origin 参数指定消息应该发送到的目标来源(URI);这有助于确保消息只传递给预期的收件人。

可以使用 postMessage() 的一些常见场景包括:

跨域通信:当两个不同的域想要相互通信时,可以使用 postMessage() 来回传递消息。

基于事件的通信:应用程序可以使用 postMessage() 将更新或事件通知发送到应用程序的其他部分或同一域中的其他窗口/选项卡。

iframe 通信:嵌入式 iframe 可以使用 postMessage() 将信息发送到其父窗口,从而允许它与页面的其余部分进行交互。

与服务器端代码通信:postMessage() 可用于与服务器端代码(例如后端 API 或网络工作者)通信。

请务必注意,应谨慎使用 postMessage() 并采取适当的安全措施,因为恶意脚本可能会使用它来获取敏感信息或执行未经授权的操作。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

4 participants