Cross domain iframe communication using window.postMessage

In HTML5 we have methods, window.postMessage and window.receiveMessage, which can be use to pass messages to different frames in a HTML document.

These two frame can belong to two different domains as well.

To send a message to a window, we will have to use window.postMessage

Lets say this frame is from url http://www.techmcq.com and trying to post a message to another frame http://www.example.com.
And this frame is opened as an iframe in http://www.example.com document.

top.postMessage('Hello','http://www.example.com');


The above code will pass a string "Hello" to frame (http://www.example.com), note we have used top instead of parent.

and top frame need an event to catch this message as well.

window.addEventListener("message", receiveMessage, false);  

function receiveMessage(event)
{
    if (event.origin !== "http://www.techmcq.com") //checking for the origin of the message
        return;
    if(event.data == 'Hello') //check for the message
    {
        alert("Hello from http://www.techmcq.com");
    }
}



In a similar way we can send message from parent frame to child frame.
Add Comments :

asdasd 21 Jun 18

asd

sadf 22 Jan 18

asfd

rty 14 Jan 18

yut

vxcvx 07 Jan 18

fsfsdfsdfsd

vxcvx 07 Jan 18

xcvxcvcx

vxcvx 07 Jan 18

cxvxvcx

Login

Register