Search code examples
javascriptpostmessage

How to get reference to the iframe that posted given message?


Main window is receiving messages from iframes nested inside it.

window.addEventListener("message", function(e){
 alert(e.data);
}, true);

How I can know from which DOM element the message has come ? The thing is that I have several of them in the document and all of them are from the same domain, but different domain from main window.


Solution

  • In the Firefox implementation of the message passing code (and maybe others), the event object has "uri" and "domain" properties you can examine, and a "source" property that refers to the originating window object.

    window.addEventListener("message", function(e){
        var frames = window.frames;
        for (var i = 0; i < frames.length; ++i)
            if (frames[i] === e.source) {
                // found it ...
            }
    }