无法获取MessageEvent属性

时间:2017-10-01 02:49:58

标签: javascript postmessage

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'
}

为什么我无法获取消息的属性?

1 个答案:

答案 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;
&#13;
&#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