PostMessage Api Send Custom Events and Message Between Parent Window to Child Iframe

Paas event from iframe to parent window and vise versa

Some time we stuck how to do some change outside the iframe on iframe click event or on click of iframe button make change in its parent window, its not easy to write some code and on iframe DOM event you can change its parent iframe.

So we can resolve this by using PostMessage API which we can also say Cross Browser iframe postMessage

by Sending messages from child iframe to parent webpage

The window.postMessage() method enables cross-origin communication between Window objects; e.g. like a iframe embedded within the page

Pass data or event message from parent window to child iframe

below is the method by which we can pass message from parent window to child iframe

we can set any message for out check and conditions let go through the below example

in above usecase code when we click on a button it will send a message button-clicked to its child iframe on the basis of this we can do any changes in our child iframe

check the below code of child iframe page which is embedded inside the parent body

Paas data or event message from child iframe to parent window

To send data events from child iframe to parent window we use window.parent.postMessage() below is the code

to send event from child to iframe we use parent object as mentioned above, lets do the same example by implimenting button in child iframe and we need to send event to parent window

iframe.html

here we have use a message window.parent.postMessage(message, “iframechiledEvent”);

Now we will capture this data event into parent window

so as conclusion to send data event from parent to child i frame we use the method

iframe.contentWindow.postMessage(message, “*”);

and to send data events from child iframe to parent window we will use

window.parent.postMessage(message, “*”);

Further reading