Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check from what crossdomain iframe the message (postMessage) came?

I know that the MessageEvent has source property which is the window object that send the message. Now how to having this information check what iframe in the main document (and of course within the main document on message arrival) was the source of that particular message ? Is only available option to check location.href on the event.source window object and then loop all the iframes to check which is matching ? What if there are iframes with the same source url in the main document ?

like image 329
rsk82 Avatar asked Sep 11 '12 22:09

rsk82


2 Answers

Iterate over all the iframes on a page and do an identity comparison on their window objects.

window.addEventListener('message', function(e) {
    if(e.origin === 'https://www.example.com') {
        var iframes = document.getElementsByTagName('iframe');

        for(var i = 0; i < iframes.length; i++) {
            if(e.source === iframes[i].contentWindow) {
                // Do stuff with iframes[i]
            }
        }
    }
}

I believe this works in all modern browsers; I'd be interested to hear if anyone has problems with it.

like image 141
75th Trombone Avatar answered Sep 21 '22 13:09

75th Trombone


If you try to read the location.href property of a cross-domain iframe/window, this will throw an exception since it violates the same-origin policy. You can write to that property, but you cannot read. And even if that would work, you would have the problem with multiple iframes with the same URL problem, as you guessed.

Anyway, what you can do is - establish a protocol for some kind of message sending confirmation. In other words, in the iframe that receives a message X you would iterate over all the iframes in the parent document and send a message to each iframe asking "Did you send me message X?" and you would program all the iframes to respond to such questions. Of course, you would have to attach unique IDs to all messages so that you would know which iframe acknowledged that it sent which message.

I think that you have to think about why the receiver of the message needs to know who the sender was, and why it is not enough for you to know just the reference to that sender (event.source)? If there is some information known to the sender - then the sender can just send this information in the message in the first place.

like image 44
Ivan Zuzak Avatar answered Sep 19 '22 13:09

Ivan Zuzak