Search code examples
javascriptibm-cloud

Do window.postMessage() works across different app on different Servers?


So, I have an app running on Bluemix (lets say route is- myapp1.mybluemix.net) and I have a second app (route - myapp2.mybluemix.net).
Now I want to send message through

postMessage("Hello","http://myapp2.mybluemix.net") from myapp1.mybluemix.net.

If I do this with both Apps in one ear or package the server and deploy it on Bluemix. I am able to do that. But not with different apps.

I don't understand the behaviour. Please help. Following the code for App1 -

<script>  
 function Menu() {
     var child = window.open("http://myapp2.mybluemix.net/page2.jsp",'name',width=200,height=200);
   child.onload=function(){
    child.postMessage('hellow','http://myapp2.mybluemix.net/');
    }
  };
  </script>
  <input type="button" value="Try it" onclick="Menu()"/>

And for App2(which is http://myapp2.mybluemix.net/page2.jsp)-

<script type="text/javascript">
function listenMessage(msg) {
alert(msg.data);
 }
 window.addEventListener("message", listenMessage, false);

</script>
<p id="message">This is an Example!</p>

Solution

  • You've misdiagnosed the problem.

    The postMessage code itself is fine. It isn't working because you are never calling it.

    The load event can't be detected across origins.

    Have App 2 listen for its own load event and use window.opener.postMessage to announce to App 1 when it is ready.