Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect which iframe sent post message

Assume I have several iframes on the page and one of them sent a post message. Is there a simple and crossbrowser way to detect which one did it and be able to reply?

I see the source property of the message event but I am unable respond by using event.source.contentWindow.postMessage on it:

Error: Permission denied to access property 'contentWindow'

like image 933
user2281966 Avatar asked Oct 02 '13 09:10

user2281966


People also ask

What is window postMessage () used for?

The window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

What does postMessage return?

postMessage() sends a message back to the main page. The two ends can listen to messages from the other using window. addEventListener("message", (event) => {...}) .


2 Answers

You can detect IFrame without names, just use comparison iframe.contentWindow === event.source.

window.addEventListener('message', function (event) {
  var iframes = document.getElementsByTagName('IFRAME');

  for (var i = 0, iframe, win; i < iframes.length; i++) {
    iframe = iframes[i];

    // Cross-browser way to get iframe's window object
    win = iframe.contentWindow || iframe.contentDocument.defaultView;

    // Comparison
    text.innerText += iframe.src +
      (win === event.source ? ' MATCHES.\n' : ' is not our IFrame.\n');
  }
});

// Creates iframe and sends postMessage from it
function createIFrameWithMessage(id) {
  var iframe = document.createElement('IFRAME');
  iframe.src = 'javascript:parent.postMessage("IFrame #' + id + '", "*");';
  document.body.appendChild(iframe);
}

createIFrameWithMessage(1);
createIFrameWithMessage(2);
createIFrameWithMessage(3);
<p id="text"></p>
like image 78
mcmimik Avatar answered Sep 28 '22 22:09

mcmimik


iframe

<script>
    document.addEventListener('mousedown',event =>
        parent.postMessage({ name: window.name }, window.location.origin)
    );
</script>

parent window

<script>
   window.addEventListener("message", event => {
       if (event.origin != window.location.origin) return;
       console.warn(event.source.frameElement.name);
       // here you can find your iframe by name
   });
</script>
<iframe name='myname1' src='/url1'/>
<iframe name='myname2' src='/url2'/>
<iframe name='myname3' src='/url3'/>
like image 39
Дмитрий Васильев Avatar answered Sep 28 '22 21:09

Дмитрий Васильев