【问题标题】:How to add click event to a iframe with JQuery如何使用 JQuery 将点击事件添加到 iframe
【发布时间】:2010-12-09 05:54:47
【问题描述】:

我的页面上有一个 iframe,来自第三方(广告)。我想在点击该 iframe 时触发一个点击事件(以记录一些内部统计数据)。比如:

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

..基于 HTML 的:

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

我似乎无法对此进行任何修改。想法?

【问题讨论】:

    标签: jquery iframe onclick


    【解决方案1】:

    iframe 没有“onclick”事件,但您可以尝试在 iframe 中捕获文档的点击事件:

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

    编辑 虽然这并不能解决您的跨站点问题,但 FYI jQuery 已经更新,可以很好地与 iFrame 配合使用:

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

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

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

    【讨论】:

    • 谢谢,这很好用,但仅适用于我域中的内容。如果我尝试从另一个域加载第 3 方内容,则不会触发 click 事件。我在网上遇到了一些其他帖子,提到了类似的东西……基本上,你可以玩 iframe 内容,但前提是它是你自己的。我肯定只会处理第 3 方的内容。嗯,还有其他想法吗?
    • 是的,实际上。尝试在 iframe 顶部放置一个透明 div(使用位置:绝对)。然后,您可以捕获对该 div 的点击。不要忘记将它们传递给 iframe(仅当它是简单的 iframe 内容时才有效 - 如果它包含自己的偶数处理 - 不要使用此方法)。
    • 更新一下:我试过绝对定位,如果 iframe 中有第 3 方内容,所有事件都会被忽略。我不认为这会发生,但我非常感谢您提供了一些帮助。
    • 没问题 - 这就是我们来这里的目的 :) 抱歉,没有成功。
    • Archive.org 是我们的朋友。 ;^) Archived blog link
    【解决方案2】:

    我试图找到一个更独立的更好答案,所以我开始思考 JQuery 如何处理事件和自定义事件。由于点击(来自 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
            });
        });
    });
    

    【讨论】:

    • 仅当框架包含来自同一域的页面时才有效(不违反同源策略)
    【解决方案3】:

    尝试使用这个:iframeTracker jQuery Plugin,就像这样:

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

    【讨论】:

    • 唯一能帮助我捕捉嵌入式 Youtube iframe 上的点击事件。谢谢!
    【解决方案4】:

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

    看这个:

    var iframe = $('#your_iframe').contents();
    
    iframe.find('your_clicable_item').click(function(event){
       console.log('work fine');
    });
    

    【讨论】:

    • 添加一些解释,说明此答案如何帮助 OP 解决当前问题
    • 将 'your_clicable_item' 更改为 'body',这是完美的答案
    • 仅当框架包含来自同一域的页面时才有效(不违反同源策略)
    • 这对我有用,但我必须将它填充到一个函数中,然后在加载 DOM 并加载 iFrame 后调用它。谢谢@jhonatan2760
    【解决方案5】:

    您可以通过以下方式模拟焦点/单击事件。 (改编自$(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");
    })

    【讨论】:

    • 如您所说,通过将“焦点”切换为“点击”,我能够停止 YouTube 视频点击的网页音频播放。
    【解决方案6】:

    建议的答案都不适合我。我通过以下方式解决了类似的情况:

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

    css(当然准确的定位要根据应用需求而变化):

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

    当然,现在您可以在 iframe-wrapper 上捕获任何事件。

    【讨论】:

    • 这将阻止所有点击在 iframe 中注册。
    • 你是对的。它将所有点击路由到 iframe-wrapper 元素。这对我有用,因为在我的情况下 iframe 没有交互式元素,我只需要它来显示。
    【解决方案7】:

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

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

    【讨论】:

      【解决方案8】:

      可能有点旧,但这可能对尝试处理同域策略的人有用。

      let isOverIframe = null;
      $('iframe').hover(function() {
              isOverIframe = true;
          }, function() {
              isOverIframe = false;
          });
      
      $(window).on('blur', function() {
          if(!isOverIframe)
              return;
      
          // ...
      });
      

      基于https://gist.github.com/jaydson/1780598

      【讨论】:

        【解决方案9】:

        您可能会遇到一些计时问题,具体取决于您绑定点击事件的时间,但它会将事件绑定到正确的窗口/文档。不过,实际上绑定到 iframe 窗口可能会得到更好的结果。你可以这样做:

            var iframeWin = $('iframe')[0].contentWindow;
            iframeWin.name = 'iframe';
            $(iframeWin).bind('click', function(event) {
                //Do something
                alert( this.name + ' is now loaded' );
            });
        

        【讨论】:

          【解决方案10】:

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

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

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

          【讨论】:

            【解决方案11】:

            适合我的解决方案:

            var editorInstance = CKEDITOR.instances[this.editorId];
            
                        editorInstance.on('focus', function(e) {
            
                            console.log("tadaaa");
            
                        });
            

            【讨论】:

              【解决方案12】:

              您可以很容易地解决它,只需将该 iframe 包装在包装器中,并跟踪它的点击次数。

              像这样:

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

              并禁用 iframe 本身的指针事件。

              #iframe_id { pointer-events: none; }

              在此更改后,您的代码将按预期工作。

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

              【讨论】:

                猜你喜欢
                • 2013-02-11
                • 2013-06-13
                • 2019-11-17
                • 1970-01-01
                • 1970-01-01
                • 2012-04-03
                • 1970-01-01
                相关资源
                最近更新 更多