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

Why i can't get message's properties ?

Phani Kumar M
  • 4,564
  • 1
  • 14
  • 26
Yao Z
  • 13
  • 2

1 Answers1

0

If you are communicating between iFrames, you should the following message send method.

iframe.postMessage(message, '*');

A working communication between iFrames can be found below.

//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>

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

The target iFrame full source code can be found here.
http://fiddle.jshell.net/lowrey/56cwafg5/?utm_source=website&utm_medium=embed&utm_campaign=56cwafg5

Thusitha
  • 3,393
  • 3
  • 21
  • 33
  • Thanks,I know how to communicate with iframe, i can’t get event.data directly, but if assign event to a new var,I can get var.data – Yao Z Oct 01 '17 at 23:24