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 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料