Search code examples
phpiframepostmessage

postMessage across domains and php


I have an iframe at www.domain1.com/file.php that is trying to use postMessage to talk to another iframe www.domain2.com/file2.php. The php files just write some simple javascript and html.

So far I can get postMessage to work if the files are on the same domain, but not a different domain. I don't get any errors in the javascript console.

    In the sending file which is at http://www.domain1.com

alert("start");  
top.frames[0].postMessage('postit','http://www.domain1.com');     
alert("end");

 In the receiving second file which is at domain2:
    function receiver(event) {
        if (event.origin == 'http://www.domain1.com') {
            if (event.data == 'postit') {
                alert("it worked");
                alert(event.data);
            }
            else {
                alert("it failed");
                alert(event.data);
            }
        }
    }
window.addEventListener('message', receiver, false);

When domain1=domain2 it works, otherwise it does not.
I get no errors in javascript console but the message is not sent.

How do I debug this?
Does using php have something to do with it not working?


Solution

  • I think you've got your target the wrong way around.

    On domain1 the code should be:

    postMessage('postit','http://www.domain2.com');
    

    Then on domain2 allow messages from domain1

    if (event.origin == 'http://www.domain1.com') {