简体   繁体   中英

Cross Domain communication from Child (iframe) to Parent not working

I have a component within AEM (Adobe Experience Manager - a cms) on a page and I want to include this page onto another page (from a different domain) using an iframe . So in the code for the component I am using window.postMessage() and I'm trying to listen to that event in the parent. I have tried communicating the other way, parent to iframe and it worked fine, but I need to communicate the other way. So the component is a search component and when you click on a search result I want to redirect but from the parent window so I'm trying to send the URL to redirect to and then handle the redirection within the parent's JS code.

The code looks like:

(From the parent - html)

<iframe
    width="1080"
    height="700"
    id="theFrame"
    src="http://localhost:4502/content/zebra1/global/en_us/hey.html#q=print"
    frameborder="0">
</iframe>

(From the parent - js)

function receiveMessage(e)
{
    var key = e.message ? "message" : "data";
    var data = e[key];
    var redirect = JSON.parse(data);
    redirectUrl = (redirect.origin ? redirect.origin : '') + (redirect.url ?
    redirect.url : '');
    if (redirectUrl) {
        window.location.href = redirectUrl;
    }
}

window.addEventListener("message", receiveMessage, false);

(From the iframe/child - js)

goToSearchResults : function( event ){

    var windowOrigin        = location.origin;

    if( arguments[0].length == 3){
        var redirect = {
            origin: windowOrigin,
            url: arguments[0][1].url || ''
        };
        if(!$('#supportSearchWrap').data('iframe')) {
            location.replace(redirect.url);
        } else {
            window.postMessage(JSON.stringify(redirect), windowOrigin);
        }
    }
    logger.log( redirect.origin + redirect.url , this.model );

}

It's not working for me. Does anyone see what I'm doing wrong or a better way to do this?

window.postMessage - The window refers to the instance of the window object to which you're posting your message. In your case, it should be the parent of the iframe window.
You can get that reference inside the iframe using window.parent or simply parent .

Also, the targetOrigin property should match the targeted window properties. From MDN docs , it is as below.

targetOrigin Specifies what the origin of otherWindow must be for the event to be dispatched, either as the literal string "*" (indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of otherWindow's document does not match that provided in targetOrigin, the event will not be dispatched; only if all three match will the event be dispatched.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM