Search code examples
javascriptnode.jsiframecsrfsame-origin-policy

How to Use postMessage on iFrame


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.


Solution

  • 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.