【问题标题】:How to use touchstart and touchend events to track click on a cross domain iframe on mobile devices如何使用 touchstart 和 touchend 事件来跟踪移动设备上跨域 iframe 的点击
【发布时间】:2019-11-04 22:32:31
【问题描述】:

我刚刚想出了如何检测跨域 iframe 上的点击事件,但它仅适用于桌面,以下代码在检测 iframe 内的点击事件时有效,但是,我还需要它在移动设备上工作,我尝试使用touchstarttouchendevents 为该脚本添加移动支持,但它不起作用。

 //Google ADs track conversion
$( document ).ready(function() { 

        var iframeMouseOver = false;
        var iframeTouched = false;
        $("#wh-widget-send-button")
            .off("mouseover.iframe").on("mouseover.iframe", function() {
                iframeMouseOver = true;
            })
            .off("mouseout.iframe").on("mouseout.iframe", function() {
                iframeMouseOver = false;
            });

        //Add mobile support to this script
        $("#wh-widget-send-button")
            .off("touchstart").on("touchstart", function() {
                iframeTouched = true;
            })
            .off("touchend").on("touchend", function() {
                iframeTouched = false;
            });

        $(window).off("blur.iframe").on("blur.iframe", function() {
            if(iframeMouseOver || iframeTouched){
                 console.log("Iframe Clicked");
                 gtag_report_conversion();
            }
        });
});

更新

请求的HTML,它只是一个div内的简单iframe,还清除了上面的代码以专注于重要部分:

<div id="wh-widget-send-button">
  <iframe src="http://anyexternaldomain.com"></iframe>
</div>

【问题讨论】:

  • 我也可以包含 HTML 吗?
  • 如果你愿意,你可以用你的答案做一个 jsfiddle
  • 对不起。我的意思是你能包含 HTML 吗?
  • @KalimahApps 再次完成检查
  • 谢谢。我不确定您需要与 iframe 进行多少交互。只是点击 iframe 还是需要与 iframe 中的某些元素进行交互?

标签: javascript jquery iframe touch-event


【解决方案1】:

我不确定您为什么需要检查悬停或触摸。您只需检查单击并执行操作。

主要概念是通过分配pointer-events:none; 从iframe 中删除事件处理。这将使父元素wh-widget-send-button 接收所有事件,然后您可以根据需要处理它们。

你可以试试这个代码:

$(document).ready(function() {

  $("#wh-widget-send-button").off("click").on("click", function() {
    console.log("Clicked");
   // gtag_report_conversion();
  });
});
iframe
{
   pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wh-widget-send-button">
  <iframe src="http://anyexternaldomain.com"></iframe>
</div>

【讨论】:

  • 这段代码的问题在于,虽然它确实“工作”,因为它检测到 iframe 上的点击,但它无法与 iframe 中的任何内容进行交互,我认为这就是为什么OP说它不起作用。
【解决方案2】:

不幸的是,您尝试做的事情是不可能的。 Web 浏览器的开发人员故意这样做,以避免点击劫持的恶意行为。您无法捕捉进入 iframe 的点击。您目前在桌面上所做的只是跟踪鼠标是否悬停在 iframe 上,而不是它是否被实际点击。不幸的是,您甚至无法在移动设备上执行此操作,因为触摸屏上的触摸会自动传输到 iframe,因此不存在适用于触摸屏的“悬停”这样的概念。很抱歉给你带来坏消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 2019-07-24
    • 2015-01-13
    • 1970-01-01
    相关资源
    最近更新 更多