Search code examples
javascriptpostmessage

Can't get MessageEvent properties


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 ?


Solution

  • 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