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

跨域和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?

图片转代码服务由CSDN问答提供 功能建议

我在www.domain1.com/file.php上有一个iframe尝试使用postMessage与另一个人交谈 iframe www.domain2.com/file2.php。 php文件只写了一些简单的javascript和html。

到目前为止,如果文件位于同一个域,但不是一个不同的域,我可以使postMessage工作。 我在javascript控制台中没有出现任何错误。

 在发送文件中,位于http://www.domain1.com 
 
alert(“start”  );  
top.frames [0] .postMessage( 'postit',的 'http://www.domain1.com');  
alert(“end”); 
 
在domain2的接收第二个文件中:
函数接收者(事件){
 if(event.origin =='http://www.domain1.com'  ){
 if(event.data =='postit'){
 alert(“it working”); 
 alert(event.data); 
} 
 else {
 alert(“it failed”)  ); 
 alert(event.data); 
} 
} 
} 
window.addEventListener('message',receiver,false); 
   
 
 

当domain1 = domain2时它可以工作,否则它不会。
我在javascript控制台中没有错误,但是没有发送消息。

如何调试?
使用php有什么关系吗?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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') {
    
    点赞 评论

相关推荐 更多相似问题