2014-06-11 51 views
0

我有一個iframe在www.domain1.com/file.php試圖使用postMessage與另一個iframe www.domain2.com/file2.php交談。 PHP文件只是寫一些簡單的JavaScript和HTML。postMessage跨域和php

到目前爲止,我可以讓postMessage工作,如果文件在同一個域,但不是一個不同的域。我沒有在JavaScript控制檯中發現任何錯誤。

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); 

當domain1 = domain2它工作,否則它不會。
我在javascript控制檯中沒有得到任何錯誤,但消息沒有發送。

如何調試?
使用PHP有沒有辦法與它不工作?

+0

讀約JSONP http://json-p.org/ – num8er

+0

這是故意機構消息 – Dave

回答

2

我認爲你的目標是錯誤的。

在domain1的代碼應該是:

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

然後在域2允許從domain1的

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

嗯。看起來你是絕對正確的。謝謝。 – techdog