How to communicate between iframe and the parent site?

前端 未结 6 719
北海茫月
北海茫月 2020-11-22 13:01

The website in the iframe isn\'t located in the same domain, but both are mine, and I would like to communicate between the iframe and the pare

6条回答
  •  情书的邮戳
    2020-11-22 13:22

    With different domains, it is not possible to call methods or access the iframe's content document directly.

    You have to use cross-document messaging.

    For example in the top window:

     myIframe.contentWindow.postMessage('hello', '*');
    

    and in the iframe:

    window.onmessage = function(e){
        if (e.data == 'hello') {
            alert('It works!');
        }
    };
    

    If you are posting message from iframe to parent window

    window.top.postMessage('hello', '*')
    

提交回复
热议问题