Which iframe posted a message to my window?

What do you do if you have a bunch of different iframes in your web page posting messages? How do you know which iframe a message came from? Even if the iframe document comes from a different origin?

This does the trick

   
window.addEventListener ("message",
  function (event) {
    /* for security, always check the origin */
    if (event.origin === 'https://www.example.com') {
    /* list of all iframes in the document */
    var iframes = document.getElementsByTagName('iframe')
    for (var i = 0; i<iframes.length; i++) {
      /* examine each iframe in turn */
      var iframe = iframes[i]
      /* does the message source match this iframe ? */
      if( event.source === iframe.contentWindow ) {
        /* get its id. other attributes are also accessible */
        var iframeId = iframe.getAttribute( 'id')
        console.log( event.data, 'from', iframeId )
      }
    }
  }
}, false );

Leave a Reply

Your email address will not be published. Required fields are marked *