简体   繁体   中英

(cross-domain) Call parent function from outside iframe is forbidden

...but I do control part of the javascript inside the second domain (which integrates the iframe). So, what I need is some workaround my problem. We have example2.com (this one holds the iframe) and example.com (this one is the original, within the iframe). Inside the iframe the user clicks a button that executes parent.redirectUser() and although I have that function defined in example2.com it fails to execute because it points the function as forbidden to access from within the iframe. Considering I can control the javascript in example2.com, is there any other way to workaround this situation? Thank you very much for your help...

Yes, you can do it. You can use messages technique, send message from child(example2.com):

parent.postMessage("Ok", "example.com");

in parent(example.com) you must add the following code:

    //add eventlistener for message event
    if (window.addEventListener) {
        window.addEventListener("message", listener);
    } else {
        // IE8
        window.attachEvent("onmessage", listener);
    }
    function listener(event) {
//check the message trust or not?
        if (event.data == "Ok") {
//from parent you can call function, but function must be placed in global scope
            redirectUser();
        }
    }

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