首页 > 解决方案 > 将事件侦听器添加到文档中的所有框架

问题描述

我正在做一些事情,这需要我在文档加载时将鼠标/键盘事件侦听器添加到文档中。

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”等方法的对象。

任何帮助将不胜感激。谢谢你。

标签: javascriptjqueryhtml

解决方案


我建议递归检查框架并附加侦听器。这确实不应该这样做,但这是唯一的方法。请注意,由于片段的沙盒限制,此片段不适用于 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>


推荐阅读