如何使用JQuery将click事件添加到iframe

时间:2022-02-25 04:50:02

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,来自第三方(广告)。我想在点击iframe时发出点击事件(记录一些内部统计数据)。就像是:

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

..based on HTML of:

..基于HTML:

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

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

我似乎无法得到任何变化的工作。思考?

9 个解决方案

#1


32  

There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:

iframe没有'onclick'事件,但您可以尝试在iframe中捕获文档的click事件:

document.getElementById("iframe_id").contentWindow.document.body.onclick = 
function() {
  alert("iframe clicked");
}

EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:

编辑虽然这不能解决您的跨站点问题,但FYI jQuery已更新为与iFrames配合使用:

$('#iframe_id').on('click', function(event) { });

Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.

更新1/2015 iframe说明的链接已被删除,因为它已不再可用。

Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.

注意如果iframe来自与主机页面不同的域,则上述代码将不起作用。您仍然可以尝试使用评论中提到的黑客。

#2


14  

Try using this : iframeTracker jQuery Plugin, like that :

尝试使用:iframeTracker jQuery插件,就像这样:

jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when iframe is clicked (like firing an XHR request)
        }
    });
});

#3


11  

I was trying to find a better answer that was more standalone, so I started to think about how JQuery does events and custom events. Since click (from JQuery) is just any event, I thought that all I had to do was trigger the event given that the iframe's content has been clicked on. Thus, this was my solution

我试图找到一个更独立的更好的答案,所以我开始考虑JQuery如何做事件和自定义事件。由于click(来自JQuery)只是任何事件,我认为所有我必须做的就是触发事件,因为已经点击了iframe的内容。因此,这是我的解决方案

$(document).ready(function () {
    $("iframe").each(function () {
        //Using closures to capture each one
        var iframe = $(this);
        iframe.on("load", function () { //Make sure it is fully loaded
            iframe.contents().click(function (event) {
                iframe.trigger("click");
            });
        });

        iframe.click(function () {
            //Handle what you need it to do
        });
    });
});

#4


6  

It works only if the frame contains page from the same domain (does not violate same-origin policy)

仅当框架包含来自同一域的页面时才有效(不违反同源策略)

See this:

看到这个:

var iframe = $('#your_iframe').contents();

iframe.find('your_clicable_item').click(function(event){
   console.log('work fine');
});

#5


1  

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):

css(当然精确定位应根据应用程序要求而改变):

#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.

当然,现在您可以在iframe包装器上捕获任何事件。

#6


1  

You can use this code to bind click an element which is in iframe.

您可以使用此代码绑定单击iframe中的元素。

jQuery('.class_in_iframe',jQuery('[id="id_of_iframe"]')[0].contentWindow.document.body).on('click',function(){	
	console.log("triggered !!")
});

#7


0  

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

您可以通过具有以下内容来模拟焦点/单击事件。 (改编自影响Iframe的$(窗口).blur事件)

$(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");
})

#8


-1  

This may be interesting for ppl using Primefaces (which uses CLEditor):

对于使用Primefaces(使用CLEditor)的ppl,这可能很有趣:

document.getElementById('form:somecontainer:editor')
.getElementsByTagName('iframe')[0].contentWindow
.document.onclick = function(){//do something}

I basically just took the answer from Travelling Tech Guy and changed the selection a bit .. ;)

我基本上只是从Travel Tech Guy那里得到了答案并且稍微改变了选择..;)

#9


-1  

Solution that work for me :

适合我的解决方案:

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

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

                console.log("tadaaa");

            });

#1


32  

There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:

iframe没有'onclick'事件,但您可以尝试在iframe中捕获文档的click事件:

document.getElementById("iframe_id").contentWindow.document.body.onclick = 
function() {
  alert("iframe clicked");
}

EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:

编辑虽然这不能解决您的跨站点问题,但FYI jQuery已更新为与iFrames配合使用:

$('#iframe_id').on('click', function(event) { });

Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.

更新1/2015 iframe说明的链接已被删除,因为它已不再可用。

Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.

注意如果iframe来自与主机页面不同的域,则上述代码将不起作用。您仍然可以尝试使用评论中提到的黑客。

#2


14  

Try using this : iframeTracker jQuery Plugin, like that :

尝试使用:iframeTracker jQuery插件,就像这样:

jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when iframe is clicked (like firing an XHR request)
        }
    });
});

#3


11  

I was trying to find a better answer that was more standalone, so I started to think about how JQuery does events and custom events. Since click (from JQuery) is just any event, I thought that all I had to do was trigger the event given that the iframe's content has been clicked on. Thus, this was my solution

我试图找到一个更独立的更好的答案,所以我开始考虑JQuery如何做事件和自定义事件。由于click(来自JQuery)只是任何事件,我认为所有我必须做的就是触发事件,因为已经点击了iframe的内容。因此,这是我的解决方案

$(document).ready(function () {
    $("iframe").each(function () {
        //Using closures to capture each one
        var iframe = $(this);
        iframe.on("load", function () { //Make sure it is fully loaded
            iframe.contents().click(function (event) {
                iframe.trigger("click");
            });
        });

        iframe.click(function () {
            //Handle what you need it to do
        });
    });
});

#4


6  

It works only if the frame contains page from the same domain (does not violate same-origin policy)

仅当框架包含来自同一域的页面时才有效(不违反同源策略)

See this:

看到这个:

var iframe = $('#your_iframe').contents();

iframe.find('your_clicable_item').click(function(event){
   console.log('work fine');
});

#5


1  

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):

css(当然精确定位应根据应用程序要求而改变):

#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.

当然,现在您可以在iframe包装器上捕获任何事件。

#6


1  

You can use this code to bind click an element which is in iframe.

您可以使用此代码绑定单击iframe中的元素。

jQuery('.class_in_iframe',jQuery('[id="id_of_iframe"]')[0].contentWindow.document.body).on('click',function(){	
	console.log("triggered !!")
});

#7


0  

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

您可以通过具有以下内容来模拟焦点/单击事件。 (改编自影响Iframe的$(窗口).blur事件)

$(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");
})

#8


-1  

This may be interesting for ppl using Primefaces (which uses CLEditor):

对于使用Primefaces(使用CLEditor)的ppl,这可能很有趣:

document.getElementById('form:somecontainer:editor')
.getElementsByTagName('iframe')[0].contentWindow
.document.onclick = function(){//do something}

I basically just took the answer from Travelling Tech Guy and changed the selection a bit .. ;)

我基本上只是从Travel Tech Guy那里得到了答案并且稍微改变了选择..;)

#9


-1  

Solution that work for me :

适合我的解决方案:

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

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

                console.log("tadaaa");

            });