Detect click event inside iframe

前端 未结 9 2162
刺人心
刺人心 2020-11-28 05:40

I\'m writing a plugin for TinyMCE and have a problem with detecting click events inside an iframe.

From my search I\'ve come up with this:

Loading iframe:

9条回答
  •  旧巷少年郎
    2020-11-28 05:51

    In my case there were two jQuery's, for the inner and outer HTML. I had four steps before I could attach inner events:

    1. wait for outer jQuery to be ready
    2. wait for iframe to load
    3. grab inner jQuery
    4. wait for inner jQuery to be ready

    $(function() {   // 1. wait for the outer jQuery to be ready, aka $(document).ready
        $('iframe#filecontainer').on('load', function() {   // 2. wait for the iframe to load
            var $inner$ = $(this)[0].contentWindow.$;   // 3. get hold of the inner jQuery
            $inner$(function() {   // 4. wait for the inner jQuery to be ready
                $inner$.on('click', function () {   // Now I can intercept inner events.
                    // do something
                });
            });
        });
    });
    

    The trick is to use the inner jQuery to attach events. Notice how I'm getting the inner jQuery:

            var $inner$ = $(this)[0].contentWindow.$;
    

    I had to bust out of jQuery into the object model for it. The $('iframe').contents() approach in the other answers didn't work in my case because that stays with the outer jQuery. (And by the way returns contentDocument.)

提交回复
热议问题