使用JavaScript检测Iframe中的点击
我理解,如果是跨域的,使用JavaScript检测Iframe中的点击,javascript,iframe,ads,dom-events,click-tracking,Javascript,Iframe,Ads,Dom Events,Click Tracking,我理解,如果是跨域的,iframe,则无法判断用户在该iframe中做什么。我想做的是跟踪用户是否在iframe中单击。我想象一个场景,在iframe的顶部有一个不可见的div,然后div将点击事件传递给iframe 这样的事情可能吗?如果是的话,我该怎么做呢?iframe是广告,因此我无法控制所使用的标签 这样的事情可能吗 不可以。你所能做的就是检测鼠标进入iframe,并可能(尽管不可靠)检测鼠标何时返回(即,试图找出指针在其他地方通过广告与停留在广告之间的区别) 我想象一个场景,在ifra
iframe
,则无法判断用户在该iframe中做什么。我想做的是跟踪用户是否在iframe
中单击。我想象一个场景,在iframe
的顶部有一个不可见的div
,然后div
将点击事件传递给iframe
这样的事情可能吗?如果是的话,我该怎么做呢?iframe
是广告,因此我无法控制所使用的标签
这样的事情可能吗
不可以。你所能做的就是检测鼠标进入iframe,并可能(尽管不可靠)检测鼠标何时返回(即,试图找出指针在其他地方通过广告与停留在广告之间的区别)
我想象一个场景,在iframe的顶部有一个不可见的div,div会将click事件传递给iframe
不,没有办法伪造点击事件
通过捕捉鼠标向下移动,可以防止原始单击进入iframe。如果你能确定什么时候按下鼠标按钮,你可以试着把不可见的div移到一边,这样点击就会通过。。。但也没有在鼠标落下之前触发的事件
您可以尝试猜测,例如,通过查看指针是否已停止,猜测单击可能即将到来。但是这是完全不可靠的,如果你失败了,你就失去了一次点击机会。如果用户点击/悬停或移出iframe,下面的代码将向你显示:-
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Detect IFrame Clicks</title>
<script type="text/javascript">
$(document).ready(function() {
var isOverIFrame = false;
function processMouseOut() {
log("IFrame mouse >> OUT << detected.");
isOverIFrame = false;
top.focus();
}
function processMouseOver() {
log("IFrame mouse >> OVER << detected.");
isOverIFrame = true;
}
function processIFrameClick() {
if(isOverIFrame) {
// replace with your function
log("IFrame >> CLICK << detected. ");
}
}
function log(message) {
var console = document.getElementById("console");
var text = console.value;
text = text + message + "\n";
console.value = text;
}
function attachOnloadEvent(func, obj) {
if(typeof window.addEventListener != 'undefined') {
window.addEventListener('load', func, false);
} else if (typeof document.addEventListener != 'undefined') {
document.addEventListener('load', func, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onload', func);
} else {
if (typeof window.onload == 'function') {
var oldonload = onload;
window.onload = function() {
oldonload();
func();
};
} else {
window.onload = func;
}
}
}
function init() {
var element = document.getElementsByTagName("iframe");
for (var i=0; i<element.length; i++) {
element[i].onmouseover = processMouseOver;
element[i].onmouseout = processMouseOut;
}
if (typeof window.attachEvent != 'undefined') {
top.attachEvent('onblur', processIFrameClick);
}
else if (typeof window.addEventListener != 'undefined') {
top.addEventListener('blur', processIFrameClick, false);
}
}
attachOnloadEvent(init);
});
</script>
</head>
<body>
<iframe src="www.google.com" width="100%" height="1300px"></iframe>
<br></br>
<br></br>
<form name="form" id="form" action=""><textarea name="console"
id="console" style="width: 100%; height: 300px;" cols="" rows=""></textarea>
<button name="clear" id="clear" type="reset">Clear</button>
</form>
</body>
</html>
检测IFrame点击
$(文档).ready(函数(){
var isOverIFrame=false;
函数processMouseOut(){
登录(“IFrame鼠标>>退出>覆盖>单击穆罕默德·拉德万,
您的解决方案非常优雅。要在Firefox和IE中检测iframe点击,您可以使用document.activeElement和计时器的简单方法,但是……我已经在互联网上搜索了一种在Chrome和Safari中检测iframe点击的方法。在放弃的边缘,我找到了您的答案。谢谢您,先生
一些提示:
我发现您的解决方案在直接调用init()函数时更可靠,而不是通过attachOnloadEvent()调用。当然,要做到这一点,您必须仅在iframe html之后调用init()。因此它看起来像:
<script>
var isOverIFrame = false;
function processMouseOut() {
isOverIFrame = false;
top.focus();
}
function processMouseOver() { isOverIFrame = true; }
function processIFrameClick() {
if(isOverIFrame) {
//was clicked
}
}
function init() {
var element = document.getElementsByTagName("iframe");
for (var i=0; i<element.length; i++) {
element[i].onmouseover = processMouseOver;
element[i].onmouseout = processMouseOut;
}
if (typeof window.attachEvent != 'undefined') {
top.attachEvent('onblur', processIFrameClick);
}
else if (typeof window.addEventListener != 'undefined') {
top.addEventListener('blur', processIFrameClick, false);
}
}
</script>
<iframe src="http://google.com"></iframe>
<script>init();</script>
$('iframe').contents().click(function(){function to record click here });
var isOverIFrame=false;
函数processMouseOut(){
isOverIFrame=false;
top.focus();
}
函数processMouseOver(){isOverIFrame=true;}
函数processIFrameClick(){
if(isOverIFrame){
//点击
}
}
函数init(){
var元素=document.getElementsByTagName(“iframe”);
对于(var i=0;i我相信您可以执行以下操作:
<script>
var isOverIFrame = false;
function processMouseOut() {
isOverIFrame = false;
top.focus();
}
function processMouseOver() { isOverIFrame = true; }
function processIFrameClick() {
if(isOverIFrame) {
//was clicked
}
}
function init() {
var element = document.getElementsByTagName("iframe");
for (var i=0; i<element.length; i++) {
element[i].onmouseover = processMouseOver;
element[i].onmouseout = processMouseOut;
}
if (typeof window.attachEvent != 'undefined') {
top.attachEvent('onblur', processIFrameClick);
}
else if (typeof window.addEventListener != 'undefined') {
top.addEventListener('blur', processIFrameClick, false);
}
}
</script>
<iframe src="http://google.com"></iframe>
<script>init();</script>
$('iframe').contents().click(function(){function to record click here });
使用jQuery来实现这一点。根据Mohammed Radwan的回答,我提出了以下jQuery解决方案。基本上,它所做的是跟踪iFrame用户悬停的内容。如果窗口模糊,则很可能意味着用户单击了iFrame横幅
iframe应放在带有id的div中,以确保您知道用户单击的iframe:
<div class='banner' bannerid='yyy'>
<iframe src='http://somedomain.com/whatever.html'></iframe>
<div>
。。。
当没有iframe悬停时,这将使overiFrame保持在-1;当iframe悬停时,将在包装div中设置“bannerid”。您所要做的就是检查窗口模糊时是否设置了“overiFrame”,如下所示:
非常优雅的解决方案,但有一个小缺点:如果用户在iFrame上悬停鼠标时按下ALT-F4,则会将其记录为单击。但这只发生在FireFox中,IE、Chrome和Safari没有注册
再次感谢Mohammed,这是一个非常有用的解决方案!如果iframe与您的父站点来自同一个域,那么它肯定会起作用。我还没有对跨域站点进行测试
$(window.frames['YouriFrameId']).click(function(event){ /* do something here */ });
$(window.frames['YouriFrameId']).mousedown(function(event){ /* do something here */ });
$(window.frames['YouriFrameId']).mouseup(function(event){ /* do something here */ });
如果没有jQuery,您可以尝试类似的方法,但我也没有尝试过
window.frames['YouriFrameId'].onmousedown = function() { do something here }
您甚至可以过滤您的结果:
$(window.frames['YouriFrameId']).mousedown(function(event){
var eventId = $(event.target).attr('id');
if (eventId == 'the-id-you-want') {
// do something
}
});
请参阅我冗长的解决方案,它在IE中无法可靠地工作
$(window).on('blur',function(e) {
if($(this).data('mouseIn') != 'yes')return;
$('iframe').filter(function(){
return $(this).data('mouseIn') == 'yes';
}).trigger('iframeclick');
});
$(window).mouseenter(function(){
$(this).data('mouseIn', 'yes');
}).mouseleave(function(){
$(this).data('mouseIn', 'no');
});
$('iframe').mouseenter(function(){
$(this).data('mouseIn', 'yes');
$(window).data('mouseIn', 'yes');
}).mouseleave(function(){
$(this).data('mouseIn', null);
});
$('iframe').on('iframeclick', function(){
console.log('Clicked inside iframe');
$('#result').text('Clicked inside iframe');
});
$(window).on('click', function(){
console.log('Clicked inside window');
$('#result').text('Clicked inside window');
}).blur(function(){
console.log('window blur');
});
$('<input type="text" style="position:absolute;opacity:0;height:0px;width:0px;"/>').appendTo(document.body).blur(function(){
$(window).trigger('blur');
}).focus();
$(窗口).on('blur',函数(e){
如果($(this).data('mouseIn')!='yes')返回;
$('iframe').filter(函数(){
返回$(this.data('mouseIn')=='yes';
}).trigger('iframeclick');
});
$(窗口).mouseenter(函数(){
$(this.data('mouseIn','yes');
}).mouseleave(函数(){
$(this.data('mouseIn','no');
});
$('iframe').mouseenter(函数(){
$(this.data('mouseIn','yes');
$(window.data('mouseIn','yes');
}).mouseleave(函数(){
$(this).data('mouseIn',null);
});
$('iframe')。在('iframeclick',function()上{
log(“在iframe内部单击”);
$(“#结果”).text('在iframe内单击');
});
$(窗口)。在('单击',函数()上){
log(“在窗口内单击”);
$(“#结果”).text(“在窗口内单击”);
}).blur(函数(){
log(“窗口模糊”);
});
$(“”).appendTo(document.body).blur(function(){
$(window.trigger('blur');
}).focus();
您可以通过使用窗口元素上的模糊事件来实现这一点
下面是一个jQuery插件,用于跟踪iframe上的单击(当单击iframe时,它将触发一个自定义回调函数):
像这样使用它:
jQuery(document).ready(function($){
$('.iframe_wrap iframe').iframeTracker({
blurCallback: function(){
// Do something when iframe is clicked (like firing an XHR request)
}
});
});
您可以执行此操作以将事件气泡化到父文档:
$('iframe').load(function() {
var eventlist = 'click dblclick \
blur focus focusin focusout \
keydown keypress keyup \
mousedown mouseenter mouseleave mousemove mouseover mouseout mouseup mousemove \
touchstart touchend touchcancel touchleave touchmove';
var iframe = $('iframe').contents().find('html');
// Bubble events to parent
iframe.on(eventlist, function(event) {
$('html').trigger(event);
});
});
只需扩展事件列表以获取更多事件。我遇到了这样一种情况:我必须跟踪通过iframe拉入的社交媒体按钮的单击。单击按钮时会打开一个新窗口。以下是我的解决方案:
var iframeClick = function () {
var isOverIframe = false,
windowLostBlur = function () {
if (isOverIframe === true) {
// DO STUFF
isOverIframe = false;
}
};
jQuery(window).focus();
jQuery('#iframe').mouseenter(function(){
isOverIframe = true;
console.log(isOverIframe);
});
jQuery('#iframe').mouseleave(function(){
isOverIframe = false;
console.log(isOverIframe);
});
jQuery(window).blur(function () {
windowLostBlur();
});
};
iframeClick();
这当然是可能的。这适用于Chrome、Firefox和IE11(可能还有其他)
警告:这只是一个例外
focus();
var listener = window.addEventListener('blur', function() {
if (document.activeElement === document.getElementById('iframe')) {
// clicked
}
window.removeEventListener('blur', listener);
});
window.addEventListener('blur',function(){
if(document.activeElement.id == 'CrossDomainiframeId'){
//do something :-)
}
});
var monitor = setInterval(function(){
var elem = document.activeElement;
if(elem && elem.tagName == 'IFRAME'){
clearInterval(monitor);
alert('clicked!');
}
}, 100);
$('.carousel-inner .item').each(function(e) {
var item = this;
var iFrame = $(item).find('iframe');
if (iFrame.length > 0) {
iFrame.iframeTracker({
blurCallback: function(){
// Do something when iFrame is clicked (like firing an XHR request)
onItemClick.bind(item)(); // calling regular click with right context
console.log('IFrameClick => OK');
}
});
console.log('IFrameTrackingRegistred => OK');
}
})
focus();
$(window).blur(() => {
let frame = document.activeElement;
if (document.activeElement.tagName == "IFRAME") {
// Do you action.. here frame has the iframe clicked
let frameid = frame.getAttribute('id')
let frameurl = (frame.getAttribute('src'));
}
});
document.addEventListener("visibilitychange", function () {
if (document.hidden) {
} else {
focus();
}
});
function () {
const state = {};
(function (setup) {
if (typeof window.addEventListener !== 'undefined') {
window.addEventListener('load', setup, false);
} else if (typeof document.addEventListener !== 'undefined') {
document.addEventListener('load', setup, false);
} else if (typeof window.attachEvent !== 'undefined') {
window.attachEvent('onload', setup);
} else {
if (typeof window.onload === 'function') {
const oldonload = onload;
window.onload = function () {
oldonload();
setup();
};
} else {
window.onload = setup;
}
}
})(function () {
state.isOverIFrame = false;
state.firstBlur = false;
state.hasFocusAcquired = false;
findIFramesAndBindListeners();
document.body.addEventListener('click', onClick);
if (typeof window.attachEvent !== 'undefined') {
top.attachEvent('onblur', function () {
state.firstBlur = true;
state.hasFocusAcquired = false;
onIFrameClick()
});
top.attachEvent('onfocus', function () {
state.hasFocusAcquired = true;
console.log('attachEvent.focus');
});
} else if (typeof window.addEventListener !== 'undefined') {
top.addEventListener('blur', function () {
state.firstBlur = true;
state.hasFocusAcquired = false;
onIFrameClick();
}, false);
top.addEventListener('focus', function () {
state.hasFocusAcquired = true;
console.log('addEventListener.focus');
});
}
setInterval(findIFramesAndBindListeners, 500);
});
function isFF() {
return navigator.userAgent.search(/firefox/i) !== -1;
}
function isActiveElementChanged() {
const prevActiveTag = document.activeElement.tagName.toUpperCase();
document.activeElement.blur();
const currActiveTag = document.activeElement.tagName.toUpperCase();
return !prevActiveTag.includes('BODY') && currActiveTag.includes('BODY');
}
function onMouseOut() {
if (!state.firstBlur && isFF() && isActiveElementChanged()) {
console.log('firefox first click');
onClick();
} else {
document.activeElement.blur();
top.focus();
}
state.isOverIFrame = false;
console.log(`onMouseOut`);
}
function onMouseOver() {
state.isOverIFrame = true;
console.log(`onMouseOver`);
}
function onIFrameClick() {
console.log(`onIFrameClick`);
if (state.isOverIFrame) {
onClick();
}
}
function onClick() {
console.log(`onClick`);
}
function findIFramesAndBindListeners() {
return Array.from(document.getElementsByTagName('iframe'))
.forEach(function (element) {
element.onmouseover = onMouseOver;
element.onmouseout = onMouseOut;
});
}
}
var eventListener = window.addEventListener('blur', function() {
if (document.activeElement === document.getElementById('contentIFrame')) {
toFunction(); //function you want to call on click
setTimeout(function(){ window.focus(); }, 0);
}
window.removeEventListener('blur', eventListener );
});
<input type="text" style="position:fixed;top:-1000px;left:-1000px">
<div id="message"></div>
<iframe id="iframe" src="//example.com"></iframe>
<script>
focus();
addEventListener('blur', function() {
if(document.activeElement = document.getElementById('iframe')) {
message.innerHTML += 'Clicked';
setTimeout(function () {
document.querySelector("input").focus();
message.innerHTML += ' - Reset focus,';
}, 1000);
}
});
</script>
var ifr = document.getElementById("my-iframe");
var isMouseIn;
ifr.addEventListener('mouseenter', () => {
isMouseIn = true;
});
ifr.addEventListener('mouseleave', () => {
isMouseIn = false;
});
window.document.addEventListener("visibilitychange", () => {
if (isMouseIn && document.hidden) {
console.log("Click Recorded By Visibility Change");
}
});
window.addEventListener("beforeunload", (event) => {
if (isMouseIn) {
console.log("Click Recorded By Before Unload");
}
});
var eventListener = window.addEventListener('blur', function() {
if (document.activeElement.classList && document.activeElement.classList[0] == 'contentiFrame') {
refresh(); //function you want to call on click
setTimeout(function(){ window.focus(); }, 1);
}
window.removeEventListener('blur', eventListener );
});