Triggering a jQuery event from iframe

前端 未结 3 1830
失恋的感觉
失恋的感觉 2021-02-07 06:44

Here\'s the scenario, I have events happening from within an iframe and up until now everything is working well. I just ran into the problem where I want to dispatch an event fr

相关标签:
3条回答
  • 2021-02-07 06:51

    So this will be the code that lives in your iFrame:

    $('#myElem').click(function() {
    
        window.parent.success_msg();
    
    });
    

    And this code needs to be in the parent window:

    window.success_msg = function() {
    
        // Your code goes here
    
    };
    

    You also need to be running this on a server, either localhost or hosted.

    0 讨论(0)
  • 2021-02-07 06:56

    Try this in the iframe js code

    var parentWin = $( window.parent.document.body );
    jQuery.event.trigger('eventName', parentWin.data(), parentWin );
    
    0 讨论(0)
  • 2021-02-07 07:12

    If you have jQuery loaded in the parent frame, try:

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

    If not, try this, I'm not sure if it will work but I just looked at the jQuery source and think it may:

    var pBody = $( parent.document.body );
    pBody.trigger( 'eventName', pBody.data() );
    

    (And do the same thing when binding eventName) The issue, as far as I can tell, is that jQuery is using the data from the local page, which is causing issues because it looks like it's trying to load data from the other frame. In other words, it's a mess, but there are data params accepted in .bind, .trigger, etc.

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