简体   繁体   English

确定是否在DOM内部的元素上附加了函数

[英]Determining whether or nor there is a function attached to an element inside the DOM

I have a question on how we can possibly figure out which elements, among existing ones on the DOM, have an attached function through 'EventListener'. 我有一个问题,我们如何才能找出DOM中现有元素中的哪些元素通过'EventListener'具有附加功能。 I know that it is not easy at all and I know that I can check it using Visual Event . 我知道这一点都不容易,而且我知道可以使用Visual Event进行检查。 But, I would like to know how Browsers or even more interesting, how Visual Event can detect that? 但是,我想知道浏览器如何甚至更有趣,Visual Event如何检测到这一点?

Let's say we are going to load a webpage and extract all the clickable elements from the DOM. 假设我们要加载网页并从DOM中提取所有可点击的元素。 How possibly we can determine that some of the existing elements won't change the status of the DOM? 我们怎么可能确定某些现有元素不会改变DOM的状态?

For example, if we don't know anything about the elements, we would need to try to click even on P tags since there might be some functions attached to those. 例如,如果我们对元素一无所知,我们甚至需要尝试单击P标签,因为这些标签可能附加了一些功能。 But, if we can determine whether or not this particular element will do anything after clicking on that, then we would be able to ignore it if it is not going to do anything. 但是,如果我们可以确定该特定元素在单击后是否会做任何事情,那么如果它不做任何事情,我们将可以忽略它。

Is there any straight way by which we can do something which Visual Event is doing? 我们可以通过什么直接方法来实现Visual Event正在做的事情?

There are no built-in functions that support this. 没有内置功能支持此功能。

The neatest way I know of is to overwrite the addEventListener method on Element.prototype with your own method that records the additions/removals of event listeners on DOM nodes. 我知道的最干净的方法是用您自己的方法覆盖Element.prototype上的addEventListener方法,该方法记录DOM节点上事件侦听器的添加/删除。 You can then expose a function to enumerate them. 然后,您可以公开一个函数来枚举它们。

This modification will of course need to be run before the relevant event listener activity in your application. 当然,需要在应用程序中的相关事件侦听器活动之前运行此修改。

See How to find event listeners on a DOM node when debugging or from the JavaScript code? 请参阅调试或从JavaScript代码时如何在DOM节点上查找事件侦听器?

Note that Chrome has built in support for this functionality via getEventListeners and a dedicated UI in the dev tools. 请注意,Chrome通过getEventListeners和开发工具中的专用UI内置了对此功能的支持。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM