window.addEventListener('message', function (message) {
console.log(message.data) // undefined
}
window.addEventListener('message', function (message) {
var myMessage = message
console.log(myMessage.data) // 'success get data'
}
为什么我无法获取消息的属性?
答案 0 :(得分:0)
如果您在iFrames
之间进行通信,则应使用以下消息send
方法。
iframe.postMessage(message, '*');
iFrames
之间的工作沟通可以在下面找到。
//Send message to the iFrame
window.send = function() {
var iframe = document.getElementById('jsfiddle-frame').contentWindow;
var message = document.querySelector('#textOutput').value;
iframe.postMessage(message, '*');
}
//Listen into the messages from the iFrame
window.addEventListener('message', function(event) {
document.querySelector('#textOutput').value = event.data;
}, false);

<div>
<h3>
Source
</h3>
<div class="output">
<textarea id='textOutput' rows="7" placeholder="Enter text and send..."></textarea>
<button onclick="send()">
Send
</button>
</div>
</div>
<hr>
<h3>
Target iFrame
</h3>
<iframe width="100%" height="300" id="jsfiddle-frame" src="//fiddle.jshell.net/lowrey/56cwafg5/5/show/light/" frameborder="0"></iframe>
&#13;
在iFrame中,
var parent = null;
window.send = function() {
if (parent) {
var message = document.querySelector('#textOutput').value;
parent.postMessage(message, '*');
}
}
window.addEventListener('message', function(event) {
parent = event.source;
document.querySelector('#textOutput').value = event.data;
}, false);
目标iFrame完整源代码可在此处找到。
http://fiddle.jshell.net/lowrey/56cwafg5/?utm_source=website&utm_medium=embed&utm_campaign=56cwafg5