使用 JavaScript 检测点击 Iframe
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2381336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect Click into Iframe using JavaScript
提问by Russ Bradberry
I understand that it is not possible to tell what the user is doing inside an iframeif it is cross domain. What I would like to do is track if the user clicked at all in the iframe. I imagine a scenario where there is an invisible divon top of the iframeand the the divwill just then pass the click event to the iframe.
我知道iframe如果是跨域,则无法判断用户在内部做什么。我想做的是跟踪用户是否在iframe. 我想象这样一个场景,还有一个看不见div的顶部iframe和的div单击事件只会然后传递给iframe。
Is something like this possible? If it is, then how would I go about it? The iframesare ads, so I have no control over the tags that are used.
这样的事情可能吗?如果是,那我该怎么办?的iframes是广告,所以我必须在所使用的标签没有控制权。
采纳答案by bobince
Is something like this possible?
这样的事情可能吗?
No. All you can do is detect the mouse going into the iframe, and potentially (though not reliably) when it comes back out (ie. trying to work out the difference between the pointer passing over the ad on its way somewhere else versus lingering on the ad).
不。您所能做的就是检测进入 iframe 的鼠标,以及可能(尽管不可靠)当它返回时(即尝试计算出在其他地方经过广告的指针与挥之不去的指针之间的区别)在广告上)。
I imagine a scenario where there is an invisible div on top of the iframe and the the div will just then pass the click event to the iframe.
我想象一个场景,在 iframe 顶部有一个不可见的 div,然后 div 将点击事件传递给 iframe。
Nope, there is no way to fake a click event.
不,没有办法伪造点击事件。
By catching the mousedown you'd prevent the original click from getting to the iframe. If you could determine when the mouse button was about to be pressed you could try to get the invisible div out of the way so that the click would go through... but there is also no event that fires just before a mousedown.
通过捕捉mousedown,您将阻止原始点击进入iframe。如果您可以确定鼠标按钮何时将被按下,您可以尝试将不可见的 div 移开,以便点击可以通过......但也没有在鼠标按下之前触发的事件。
You could try to guess, for example by looking to see if the pointer has come to rest, guessing a click might be about to come. But it's totally unreliable, and if you fail you've just lost yourself a click-through.
您可以尝试猜测,例如通过查看指针是否已停止,猜测可能即将出现点击。但它完全不可靠,如果你失败了,你就失去了一个点击通过的机会。
回答by Paul Draper
This is certainly possible. This works in Chrome, Firefox, and IE 11 (and probably others).
这当然是可能的。这适用于 Chrome、Firefox 和 IE 11(可能还有其他)。
focus();
var listener = window.addEventListener('blur', function() {
if (document.activeElement === document.getElementById('iframe')) {
// clicked
}
window.removeEventListener('blur', listener);
});
Caveat: This only detects the first click. As I understand, that is all you want.
警告:这只检测第一次点击。据我了解,这就是你想要的。
回答by patrick
Based on Mohammed Radwan's answer I came up with the following jQuery solution. Basically what it does is keep track of what iFrame people are hovering. Then if the window blurs that most likely means the user clicked the iframe banner.
基于 Mohammed Radwan 的回答,我想出了以下 jQuery 解决方案。基本上它的作用是跟踪 iFrame 人们正在悬停的内容。然后,如果窗口模糊,则很可能意味着用户单击了 iframe 横幅。
the iframe should be put in a div with an id, to make sure you know which iframe the user clicked on:
iframe 应该放在一个带有 id 的 div 中,以确保您知道用户单击了哪个 iframe:
<div class='banner' bannerid='yyy'>
<iframe src='http://somedomain.com/whatever.html'></iframe>
<div>
so:
所以:
$(document).ready( function() {
var overiFrame = -1;
$('iframe').hover( function() {
overiFrame = $(this).closest('.banner').attr('bannerid');
}, function() {
overiFrame = -1
});
... this keeps overiFrame at -1 when no iFrames are hovered, or the 'bannerid' set in the wrapping div when an iframe is hovered. All you have to do is check if 'overiFrame' is set when the window blurs, like so: ...
...当没有 iFrame 悬停时,这将 overiFrame 保持在 -1,或者在 iframe 悬停时在包装 div 中设置的“bannerid”。您所要做的就是检查窗口模糊时是否设置了“overiFrame”,如下所示:...
$(window).blur( function() {
if( overiFrame != -1 )
$.post('log.php', {id:overiFrame}); /* example, do your stats here */
});
});
Very elegant solution with a minor downside: if a user presses ALT-F4 when hovering the mouse over an iFrame it will log it as a click. This only happened in FireFox though, IE, Chrome and Safari didn't register it.
非常优雅的解决方案,但有一个小缺点:如果用户在将鼠标悬停在 iFrame 上时按下 ALT-F4,它会将其记录为点击。这只发生在 FireFox 中,IE、Chrome 和 Safari 没有注册它。
Thanks again Mohammed, very useful solution!
再次感谢穆罕默德,非常有用的解决方案!
回答by Dmitry Kochin
This is small solution that works in all browsers even IE8:
这是一个适用于所有浏览器甚至 IE8 的小解决方案:
var monitor = setInterval(function(){
var elem = document.activeElement;
if(elem && elem.tagName == 'IFRAME'){
clearInterval(monitor);
alert('clicked!');
}
}, 100);
You can test it here: http://jsfiddle.net/oqjgzsm0/
你可以在这里测试:http: //jsfiddle.net/oqjgzsm0/
回答by Mohammed Radwan
The following code will show you if the user click/hover or move out of the iframe:-
如果用户单击/悬停或移出 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>
You need to replace the src in the iframe with your own link. Hope this'll help. Regards, Mo.
您需要将 iframe 中的 src 替换为您自己的链接。希望这会有所帮助。问候,莫。
回答by Tony
Just found this solution... I tried it, I loved it..
刚刚找到这个解决方案......我试过了,我喜欢它......
Works for cross domain iframes for desktop and mobile!
适用于桌面和移动设备的跨域 iframe!
Don't know if it is foolproof yet
不知道是不是万无一失
window.addEventListener('blur',function(){
if(document.activeElement.id == 'CrossDomainiframeId'){
//do something :-)
}
});
Happy coding
快乐编码
回答by DiverseAndRemote.com
see http://jsfiddle.net/Lcy797h2/for my long winded solution that doesn't work reliably in IE
请参阅http://jsfiddle.net/Lcy797h2/,了解我在 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();
回答by Vince
You can achieve this by using the blur event on window element.
您可以通过在 window 元素上使用 blur 事件来实现这一点。
Here is a jQuery plugin for tracking click on iframes (it will fire a custom callback function when an iframe is clicked) : https://github.com/finalclap/iframeTracker-jquery
这是一个用于跟踪 iframe 单击的 jQuery 插件(单击 iframe 时会触发自定义回调函数):https: //github.com/finalclap/iframeTracker-jquery
Use it like this :
像这样使用它:
jQuery(document).ready(function($){
$('.iframe_wrap iframe').iframeTracker({
blurCallback: function(){
// Do something when iframe is clicked (like firing an XHR request)
}
});
});
回答by sidanmor
This works for me on all browsers (included Firefox)
这适用于所有浏览器(包括 Firefox)
https://gist.github.com/jaydson/1780598
https://gist.github.com/jaydson/1780598
https://jsfiddle.net/sidanmor/v6m9exsw/
https://jsfiddle.net/sidanmor/v6m9exsw/
var myConfObj = {
iframeMouseOver : false
}
window.addEventListener('blur',function(){
if(myConfObj.iframeMouseOver){
console.log('Wow! Iframe Click!');
}
});
document.getElementById('idanmorblog').addEventListener('mouseover',function(){
myConfObj.iframeMouseOver = true;
});
document.getElementById('idanmorblog').addEventListener('mouseout',function(){
myConfObj.iframeMouseOver = false;
});
<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>
<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>
<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>
回答by Taner Topal
You can do this to bubble events to parent document:
您可以这样做以将事件冒泡到父文档:
$('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);
});
});
Just extend the eventlist for more events.
只需扩展事件列表以获取更多事件。

