Search code examples
javascriptpostmessage

sending Messages from one domain to another using postMessage function in javascript


If i open one domain chat.example.com in one browser and www.example.com(cross domain) on other browser. is it possible send a message from www.abc.com to chat.abc.com?

I tried following:

The script on receiver side i.e.www.example.com to receive message as follows:

jqcc(document).ready(function() {

var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
if(e.data.indexOf("He") >= -1){
    console.log("Message Received:"+e.data);
}

},false);

});

When i try sending message from http://chat.example.com as

window.postMessage("Hello","http://www.example.com");

I got nothing in the console of browser. Please help


Solution

  • No, it won't work.

    The postMessage api is to be used with iframes only. What you want to do is open an iframe to www.chat.example.com inside www.example.com. Then, you can use document.getElementById('iframe_pointing_to_chat').contentWindow.postMessage('message', '*').

    Now, the www.chat.example.com will receive the message via the onmessage handler.