Trigger Custom Event From Iframe To Parent Document

前端 未结 4 2233
别跟我提以往
别跟我提以往 2020-12-07 22:54

I am having some trouble to fire a custom event inside an iframe and detect it from the parent document. Both iframe and parent document have the same origin (same protocol,

相关标签:
4条回答
  • 2020-12-07 23:24

    A consistent answer supporting both same-domain and cross-domain iframes is to use event system.

    The goal is to send a custom event from iframe to parent.

    In the iframe source file:

    var myCustomData = { foo: 'bar' }
    var event = new CustomEvent('myEvent', { detail: myCustomData })
    window.parent.document.dispatchEvent(event)
    

    And add this in the parent file which contains the iframe:

    window.document.addEventListener('myEvent', handleEvent, false)
    function handleEvent(e) {
      console.log(e.detail) // outputs: {foo: 'bar'}
    }
    
    0 讨论(0)
  • 2020-12-07 23:25

    I have also find my way to solve this problem with jquery:

    in parent file:

    <body>
            <iframe src="something.html"></iframe>
    
    </body>
    
    <script>
     window.document.addEventListener('event', function(e){
                console.log("event:" + e.detail);
                $("iframe").contents().find(".class[title='" + e.detail + "']").css(someChanges);
    </script>
    
    

    so you don't need to add any other EventListener in your iFrames.

    of course maybe you want see my CustomEvent:

    var test  = "1";
    var event = new CustomEvent('event', { detail: test })
                    window.document.dispatchEvent(event);
    

    I hope I could help somebody...

    0 讨论(0)
  • 2020-12-07 23:37

    I ran into a similar problem and used window.postMessage to solve.

    Currently, the API only supports passing a string, but if you modify your solution it can be powerful. More details here

    From the source page (being consumed by an iframe):
    postMessage API expects 2 params - message , target

    ex: window.parent.postMessage("HELLO_PARENT", 'http://parent.com');

    From the parent page (contains iframe. Eg Container):

    1. Add an event listener as you normally would

       window.addEventListener('message', handleMessage, false);
      
    2. Define your function with event.origin check (for security) \

       function handleMessage(event) {  
           if (event.origin != "http://child.com") { return; }  
           switch(event.data) {   
                case "HELLO_PARENT":  
                   alert("Hello Child");  
                   break;  
           } 
       }
      
    0 讨论(0)
  • 2020-12-07 23:43

    This works:

    parent.$('body').trigger('eventName');
    

    the event triggered inside the iframe will be detected in the parent document.

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