如何在 iFrame 上使用 postMessage
How to Use postMessage on iFrame
我有 2 个具有以下域的 nodeJS 应用程序:
- localhost:8000
- localhost:3000
在 localhost:3000 中,我有一个文本区域和一个提交按钮。
我想posttextarea的内容(使用postMessage)到一个localhost:8000/(some_id),并在localhost:8000 页。
然后,我想在 localhost:3000 页面中显示 localhost:8000/(some_id) 的 iFrame。
我在完成这件事时遇到了很多麻烦。我必须使用 postMessage().
以这种方式完成它
PS:我知道最好避免使用 iFrame,但是为了我的应用程序的目的,这是必须使用的。
无论你在一侧 postMessage
什么都会被发送到另一侧的 message
听众。
// in the parent document
iframeElement.contentWindow.postMessage('hi!');
// in the iframe
window.addEventListener('message', ({ data }) => {
console.log('i got some data!', data); // i got some data! hi!
});
你也可以反其道而行之,在 iframe 源代码中使用 window.parent.postMessage()
,在父文档中使用 window.addEventListener('message', ...)
监听。
我有 2 个具有以下域的 nodeJS 应用程序:
- localhost:8000
- localhost:3000
在 localhost:3000 中,我有一个文本区域和一个提交按钮。
我想posttextarea的内容(使用postMessage)到一个localhost:8000/(some_id),并在localhost:8000 页。
然后,我想在 localhost:3000 页面中显示 localhost:8000/(some_id) 的 iFrame。
我在完成这件事时遇到了很多麻烦。我必须使用 postMessage().
以这种方式完成它PS:我知道最好避免使用 iFrame,但是为了我的应用程序的目的,这是必须使用的。
无论你在一侧 postMessage
什么都会被发送到另一侧的 message
听众。
// in the parent document
iframeElement.contentWindow.postMessage('hi!');
// in the iframe
window.addEventListener('message', ({ data }) => {
console.log('i got some data!', data); // i got some data! hi!
});
你也可以反其道而行之,在 iframe 源代码中使用 window.parent.postMessage()
,在父文档中使用 window.addEventListener('message', ...)
监听。