Detect click event inside iframe

2020-01-26 04:19发布

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:

<iframe src='resource/file.php?mode=tinymce' id='filecontainer'></iframe>

HTML inside iframe:

<input type=button id=choose_pics value='Choose'>

jQuery:

//Detect click
$("#filecontainer").contents().find("#choose_pic").click(function(){
    //do something      
}); 

Other posts I've seen usually have a problem with different domains (this hasn't). But, still, the event isn't detected.

Can something like this be done?

9条回答
等我变得足够好
2楼-- · 2020-01-26 05:14

The tinymce API takes care of many events in the editors iframe. I strongly suggest to use them. Here is an example for the click handler

// Adds an observer to the onclick event using tinyMCE.init
tinyMCE.init({
   ...
   setup : function(ed) {
      ed.onClick.add(function(ed, e) {
           console.debug('Iframe clicked:' + e.target);
      });
   }
});
查看更多
神经病院院长
3楼-- · 2020-01-26 05:16
$("#iframe-id").load( function() {
    $("#iframe-id").contents().on("click", ".child-node", function() {
        //do something
    });
});
查看更多
啃猪蹄的小仙女
4楼-- · 2020-01-26 05:21

In my case, I was trying to fire a custom event from the parent document, and receive it in the child iframe, so I had to do the following:

var event = new CustomEvent('marker-metrics', {
    detail: // extra payload data here
});
var iframe = document.getElementsByTagName('iframe');
iframe[0].contentDocument.dispatchEvent(event)

and in the iframe document:

document.addEventListener('marker-metrics', (e) => {
  console.log('@@@@@', e.detail);
});
查看更多
登录 后发表回答