最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to Use postMessage on iFrame - Stack Overflow

programmeradmin1浏览0评论

I have 2 nodeJS applications with the following domains:

  • localhost:8000
  • localhost:3000

In localhost:3000, I have a textarea, and a submit button.

I want to post the contents of the textarea (using postMessage) to a localhost:8000/(some_id), and display the contents on the localhost:8000 page.

Then, I want to show an iFrame of the localhost:8000/(some_id) in the localhost:3000 page.

I am having a lot of trouble accomplishing this. I must accomplish it in this way using postMessage().

PS: I know it is probably best to avoid iFrames, however for the purpose of my application, this is necessary to use.

I have 2 nodeJS applications with the following domains:

  • localhost:8000
  • localhost:3000

In localhost:3000, I have a textarea, and a submit button.

I want to post the contents of the textarea (using postMessage) to a localhost:8000/(some_id), and display the contents on the localhost:8000 page.

Then, I want to show an iFrame of the localhost:8000/(some_id) in the localhost:3000 page.

I am having a lot of trouble accomplishing this. I must accomplish it in this way using postMessage().

PS: I know it is probably best to avoid iFrames, however for the purpose of my application, this is necessary to use.

Share Improve this question asked Aug 27, 2018 at 21:28 CodeRocksCodeRocks 7155 gold badges10 silver badges26 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 18

Whatever you postMessage on one side will be sent to the message listener on the other side.

// 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!
});

You can also go the other way, and use window.parent.postMessage() in the iframe source and listen for it with window.addEventListener('message', ...) in parent document.

发布评论

评论列表(0)

  1. 暂无评论