dtrvzd1171 2014-06-11 20:02
浏览 201
已采纳

跨域和php的postMessage

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?

  • 写回答

1条回答 默认 最新

  • douni1396 2014-06-11 20:04
    关注

    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') {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?