Skip to content

Instantly share code, notes, and snippets.

@chenwery
Created February 20, 2014 06:21
Show Gist options
  • Save chenwery/9108016 to your computer and use it in GitHub Desktop.
Save chenwery/9108016 to your computer and use it in GitHub Desktop.
javascript:监听页面中iframe被点击
var IframeOnClick = {
resolution : 200,
iframes : [],
interval : null,
Iframe : function() {
this.element = arguments[0];
this.cb = arguments[1];
this.hasTracked = false;
},
track: function(element, cb) {
this.iframes.push(new this.Iframe(element, cb));
if (!this.interval) {
var _this = this;
this.interval = setInterval(function() {
_this.checkClick();
}, this.resolution);
}
},
checkClick: function() {
if (document.activeElement) {
var activeElement = document.activeElement;
for(var i in this.iframes) {
if(activeElement === this.iframes[i].element) {
if(this.iframes[i].hasTracked == false) {
this.iframes[i].cb.apply(window, []);
this.iframes[i].hasTracked = true;
}
} else {
this.iframes[i].hasTracked = false;
}
}
}
}
};
var frames = document.getElementsByTagName("iframe");
for (var i = 0; i < frames.length; i++) {
IframeOnClick.track(frames[i], function() {
jQuery(document).click();
});
}
需求:在一个页面注册了window的click事件,但是当这个页面包含一个iframe,点击这个iframe里的内容时,无法触发给上层页面window(top)注册的click事件,尤其是这个iframe指向一个跨域的地址时,无法在iframe中使用parent,这个问题就不好解决了,iframeclick.js解决了这个问题。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment