由於操作具有不同來源的幀會導致發生跨源錯誤,因此您必須使用window.postMessage()
方法將消息發送給子代,並在其中收聽window.onmessage
並處理消息。
下面是一個例子,假設你有一個DOM結構是這樣的:
網站#1(www.mysite1.com):
<body>
<iframe id="site2-frame" src="http://www.mysite2.com/index.php"></iframe>
</body>
站點#2(WWW .mysite2.com)在iframe:
<body>
<input id="input-field" />
</body>
然後在您的網站#1,你必須將消息發送到框架上,像這樣:
var frame = document.getElementById('site2-frame');
frame.contentWindow.postMessage('Something something something', '*');
而且在您的網站#2,框架中的一個,你會聽消息,設置數據:
var input = document.getElementById('input-field');
window.addEventListener('message', function(e) {
// Check the origin, accept messages only if they are from YOUR site!
if (/^http\:\/\/www\.mysite1\.com/.test(e.origin)) {
input.value = e.data;
// This will be 'Something something something'
}
});
如果這兩個網站位於不同的域名中,您必須使用[Window.postMessage](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad = RJA&uact = 8&VED = 0CB0QFjAA&URL = HTTPS%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FWindow.postMessage&EI = d42tVIDoC4b4yQSU_YLQCA&USG = AFQjCNEnazVAnZe__qabZI2Vcu1R9u8b0g&SIG2 = oSaANLF7G504jbK2667cfA)。 – JCOC611
您是否嘗試用站點2中的數據設置站點1上的輸入字段? –
試圖設置站點2的輸入字段與從站點1拉的數據 – JackNew