cross site iframe postMessage from child to parent

后端 未结 2 1018
北荒
北荒 2020-12-16 03:00

I found this samplefrom SO while browsing for my problem, but I want to know exactly how to use it in my scenario. I have an iframe which is from another domain, and I want

相关标签:
2条回答
  • 2020-12-16 03:17

    Check http://davidwalsh.name/window-iframe out. This is a perfect working example.

    The parent object provides a reference to the main window from the child. So if I have an iFrame and console the parent within it, the console will read:

    // Every two seconds....
    setInterval(function() {
        // Send the message "Hello" to the parent window
        // ...if the domain is still "davidwalsh.name"
        parent.postMessage("Hello","http://davidwalsh.name");
    }, 3000);
    

    Since we now have hold of the window, we can postMessage to it:

    // Create IE + others compatible event handler
    var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    var eventer = window[eventMethod];
    var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
    
    // Listen to message from child window
    eventer(messageEvent,function(e) {
      console.log('parent received message!:  ',e.data);
    },false);
    

    The directive above triggers the iFrame to send a message to the parent window every 3 seconds. No initial message from the main window needed!

    0 讨论(0)
  • 2020-12-16 03:19

    You need to set targetOrigin when using postMessage.

    <script type="text/javascript">
        $(document).ready(function() {
           parent.postMessage("Second Page",'*');
        }
    </script>
    

    Then on the host page.

    function addAnEventListener(obj,evt,func){
        if ('addEventListener' in obj){
            obj.addEventListener(evt,func, false);
        } else if ('attachEvent' in obj){//IE
            obj.attachEvent('on'+evt,func);
        }
    }
    
    function iFrameListener(event){
         secondPageValue = event.data;
    }
    
    var secondPageValue='';
    
    addAnEventListener(window,'message',iFrameListener);
    
    0 讨论(0)
提交回复
热议问题