javascript - 将事件侦听器添加到文档中的所有框架
问题描述
我正在做一些事情,这需要我在文档加载时将鼠标/键盘事件侦听器添加到文档中。
document/window.addEventListener()
在我遇到 Frameset/frames/iframes 之前工作得很好。
我做了一些解决方法,比如遍历框架集的所有框架并向它们添加事件侦听器。
然后我意识到框架是在 DOM 之后动态加载的。所以我做了这样的事情:
bindListenersToFrame: function(element){
var $ = domUtils.jQuery;
$(element).ready(function(){
if(element.tagName == "FRAMESET" || element.tagName == "BODY"){
for(var i=0; i < element.children.length; i++){
domUtils.bindListenersToFrame(element.children[i]);
}
}
if(element.tagName == "FRAME" || element.tagName == "IFRAME"){
$('iframe').load(function(){
domUtils.addListener(element);
if(element.contentDocument.documentElement){
for(var i=0; i < element.contentDocument.documentElement.children.length; i++){
domUtils.bindListenersToFrame(element.contentDocument.documentElement.children[i]);
}
}
});
}
});
}
上面的方法本质上是递归的,domUtils 只是一个带有“addListener”等方法的对象。
任何帮助将不胜感激。谢谢你。
解决方案
我建议递归检查框架并附加侦听器。这确实不应该这样做,但这是唯一的方法。请注意,由于片段的沙盒限制,此片段不适用于 SO。我已经对其进行了测试,它可以在本地服务器上运行。我也无法(在有限的时间内)找到解决setTimeout
我当前使用的方法。感觉就像是在页面加载之前应用了它,但是我看不到这些load
事件的任何影响,所以为了展示它是如何工作的,请检查一下:
function nestedIFrameEventAttacher( iframe, event, handler ){
const content = iframe.contentDocument || (iframe.contentWindow ? iframe.contentWindow .document : iframe);
const body = content.querySelector( 'body' );
body.addEventListener( event, handler );
// I have tried attaching `load` and `DOMContentLoaded` events
// to the `iframe` and the `body` but none of them seemed to trigger.
// This is therefor not guaranteed to work, but you can start from this.
setTimeout(function(){
Array.from( body.querySelectorAll( 'iframe' ) ).forEach(iframe => {
nestedIFrameEventAttacher( iframe, event, handler );
});
}, 100);
}
const output = document.getElementById( 'output' )
nestedIFrameEventAttacher( document, 'click', function( event ){
output.textContent = this.querySelector( 'h1' ).textContent;
});
#output{ color: red; }
<div id="output">Stealie the Dog</div>
<h1>Root</h1>
<iframe srcdoc="<html><head></head><body><h1>Second</h1><iframe srcdoc='<html><head></head><body><h1>Deeper</h2></body></html>'></iframe></body></html>" width="100%" height="500px"></iframe>
推荐阅读
- android - TGeocoder 只显示第一个标记的地址
- python - 使用 go.Scatter3d 和 Dash 进行 3D 聚类
- python - 如何根据python中的if语句跳到循环的下一次迭代?
- flutter - 是否可以禁用在颤动的可重新排序列表视图中重新排序单个项目?
- sqlite - sqlite3 select records from multiple tables
- android - 将 ImageVector 从 Jetpack Compose 转换为 BitmapDescriptor
- python - 如何找到一个数组的平均值并将其与其对应的名称固定在另一个数组中
- javascript - 在 django modelform 属性上传递 url 参数
- java - 带有 CompletableFuture 调用的 Spring 启动 - 创建名称为“scopedTarget.asyncBean”的 bean 时出错:范围“请求”
- ruby-on-rails - Azure url 编码/解码问题