How to add click event to a iframe with JQuery

2019-01-01 05:52发布

I have an iframe on a page, coming from a 3rd party (an ad). I'd like to fire a click event when that iframe is clicked in (to record some in-house stats). Something like:

$('#iframe_id').click(function() {
    //run function that records clicks
});

..based on HTML of:

<iframe id="iframe_id" src="http://something.com"></iframe>

I can't seem to get any variation of this to work. Thoughts?

10条回答
人间绝色
2楼-- · 2019-01-01 06:20

None of the suggested answers worked for me. I solved a similar case the following way:

<a href="http://my-target-url.com" id="iframe-wrapper"></a>
<iframe id="iframe_id" src="http://something.com" allowtrancparency="yes" frameborder="o"></iframe>

The css (of course exact positioning should change according to the app requirements):

#iframe-wrapper, iframe#iframe_id {
  width: 162px;
  border: none;
  height: 21px;
  position: absolute;
  top: 3px;
  left: 398px;
}
#alerts-wrapper {
  z-index: 1000;
}

Of course now you can catch any event on the iframe-wrapper.

查看更多
低头抚发
3楼-- · 2019-01-01 06:30

Solution that work for me :

var editorInstance = CKEDITOR.instances[this.editorId];

            editorInstance.on('focus', function(e) {

                console.log("tadaaa");

            });
查看更多
墨雨无痕
4楼-- · 2019-01-01 06:30

You can solve it very easily, just wrap that iframe in wrapper, and track clicks on it.

Like this:

<div id="iframe_id_wrapper"> <iframe id="iframe_id" src="http://something.com"></iframe> </div>

And disable pointer events on iframe itself.

#iframe_id { pointer-events: none; }

After this changes your code will work like expected.

$('#iframe_id_wrapper').click(function() { //run function that records clicks });

查看更多
回忆,回不去的记忆
5楼-- · 2019-01-01 06:34

You could simulate a focus/click event by having something like the following. (adapted from $(window).blur event affecting Iframe)

$(window).blur(function () {
  // check focus
  if ($('iframe').is(':focus')) {
    console.log("iframe focused");
    $(document.activeElement).trigger("focus");// Could trigger click event instead
  }
  else {
    console.log("iframe unfocused");
  }                
});

//Test
$('#iframe_id').on('focus', function(e){
  console.log(e);
  console.log("hello im focused");
})

查看更多
登录 后发表回答