How to Call Parent Window JavaScript Function inside iframe

前端 未结 2 1852
清歌不尽
清歌不尽 2020-12-10 14:09

Here is my code on http://my-localhost.com/iframe-test.html


Welcome Iframe Test         


        
相关标签:
2条回答
  • 2020-12-10 14:40

    You can use postMessage!

    PARENT

    if (window.addEventListener) {
        window.addEventListener ("message", receive, false);        
    }
    else {
        if (window.attachEvent) {
            window.attachEvent("onmessage",receive, false);
        }
    }
    
    function receive(event){
        var data = event.data;
        if(typeof(window[data.func]) == "function"){
            window[data.func].call(null, data.params[0]);
        }
    }
    
    function alertMyMessage(msg){
    
        alert(msg);
    }
    

    IFRAME

    function send(){
        window.parent.window.postMessage(
            {'func':'alertMyMessage','params':['Thanks for Helping me']},
            'http://www.my-website.com'
        );
    }
    

    REFERENCE

    https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

    0 讨论(0)
  • 2020-12-10 14:43

    You cannot access the DOM of a page loaded in a frame in a different origin. This is blocked for security reasons (imagine a random website you visited opening your web mail service in a hidden iframe and you can see why).

    The closest you can come, and then only if you control both websites, is to pass messages between them using the web messaging api.

    In one page, write a function to handle the messages and then add it as a message event listener.

    function receiveMessage(event)
    {
      alert(event.data);
    }
    
    addEventListener("message", receiveMessage, false);
    

    In the other, send the message:

    parent.postMessage("This is a message", "*");
    

    See MDN for more information

    0 讨论(0)
提交回复
热议问题