How to check from which crossdomain iframe the message (postMessage) came from?

I know that it MessageEventhas a property sourcethat is a window object that sends a message. How to find out how iframe in the main document (and, of course, in the main document when the message arrived) was the source of this message? Is only a validation option available location.hrefin the window object event.source, and then a cycle of all frames to verify compliance? What if the main document has iframes with the same source url?

+5
source share
3 answers

If you try to read the location.hrefcross-domain iframe / window property , this will throw an exception because it violates a policy of the same origin. You can write for this property, but you cannot read . And even if that works, you will have a problem with multiple iframes with the same url problem you guessed it.

, - - . , iframe, X, iframe " X?" . , , , iframe , .

, , , , (event.source)? - , .

+1

iframes window.

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]
            }
        }
    }
}

, ; , - .

+1

a more efficient way is to pass iframes to each unique identifier upon initiation and force them to use that identifier when sending back to the parent frame.

0
source

All Articles