2012-12-25 141 views
0

我想從IFRAME中每隔幾秒鐘傳遞消息給父頁面,如:的Iframe跨域問題

Iframe Domain = www.abc.com 
Parent Domain = www.xyz.com 

有檢查有:

有人可以幫我嗎?

+4

你的問題是什麼? 'postMessage'應該可以跨域使用。 – Amadan

+0

@Amadan postMessage將工作跨域,如果服務允許*(或xyz.com)。還是我誤會了? –

+0

你錯了。 「postMessage」的重點是允許陌生人之間的溝通。您不能強制其他框架執行任何尚未擁有的代碼,只需將數據發送給他們 - 他們如何處理這些數據以及他們如何驗證數據。這與在鏈接問題中引用'document.getElementById('myframe')。contentWindow.document'等東西形成對比,該鏈接問題試圖主動撬入另一個框架的事務。閱讀關於'postMessage'的更多信息[在MDN上](https://developer.mozilla.org/en-US/docs/DOM/window.postMessage)。 – Amadan

回答

1

我最近剛剛幫助另一個非常相似的人,在IFrame之間傳遞消息。 (見Issues with Cross Document Messaging between IFrame & Parent)。

使用我從suamikim中借用的代碼的修改版本,我已經集成了一個計時器。這應該是你的一個很好的起點。這些父母和子女的HTML頁面將按照上述註釋中所述的方式跨域運作,其中包括Amadan的。我只是測試並確認它,通過將parent.html上一個域,它指出child.html上的完全獨立的不可信域。

parent.html

<html> 
 
<head> 
 
    <script type="text/javascript"> 
 
     function parentInitialize() { 
 
      var count = 0; 
 
      window.addEventListener('message', function (e) { 
 
       // Check message origin etc... 
 
       if (e.data.type === 'iFrameRequest') { 
 
        var obj = { 
 
         type: 'parentResponse', 
 
         responseData: 'Response #' + count++ 
 
        }; 
 
        e.source.postMessage(obj, '*'); 
 
       } 
 
       // ... 
 
      }) 
 
\t \t } 
 
    </script> 
 
</head> 
 
<body style="background-color: rgb(72, 222, 218);" onload="javascript: parentInitialize();"> 
 
    <iframe src="child.html" style="width: 500px; height:350px;"></iframe> 
 
</body> 
 
</html>

child.html

<html> 
 
<head> 
 
    <script type="text/javascript"> 
 
     function childInitialize() { 
 
      // ... 
 

 
      try { 
 
       if (window.self === window.top) { 
 
        // We're not inside an IFrame, don't do anything... 
 
        return; 
 
       } 
 
      } catch (e) { 
 
       // Browsers can block access to window.top due to same origin policy. 
 
       // See https://stackoverflow.com/a/326076 
 
       // If this happens, we are inside an IFrame... 
 
      } 
 

 
      function messageHandler(e) { 
 
       if (e.data && (e.data.type === 'parentResponse')) { 
 
        // Do some stuff with the sent data 
 
        var obj = document.getElementById("status"); 
 
        obj.value = e.data.responseData; 
 
       } 
 
      } 
 

 
      window.addEventListener('message', messageHandler, false); 
 

 
      setInterval(function() { 
 
       window.parent.postMessage({ type: 'iFrameRequest' }, '*'); 
 
      }, 1000); 
 
      // ... 
 
     } 
 
    </script> 
 
</head> 
 
<body style="background-color: rgb(0, 148, 255);" onload="javascript: childInitialize();"> 
 
    <textarea type="text" style="width:400px; height:250px;" id="status" /> 
 
</body> 
 
</html>

祝你好運!