我刚刚想出了如何检测跨域 iframe 上的点击事件,但它只适用于桌面,以下代码在检测 iframe 内的点击事件时有效,但是,我还需要它在移动设备上工作,我尝试使用 touchstart
和 touchend
事件向该脚本添加移动支持,但它不起作用。
//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>
最佳答案
我不确定您为什么需要检查悬停或触摸。您可以只检查点击并执行操作。
主要概念是通过分配 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>
关于javascript - 如何使用 touchstart 和 touchend 事件跟踪移动设备上跨域 iframe 的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58702036/