[英]How to find where a custom event listener has been added?
There is a 3rd party piece of code running in a "friendly" iframe on a page.在页面上的“友好”iframe 中运行了一段 3rd 方代码。 The code may or may not have added a listener for one of it's own custom events to any element on the outer page, or in one of the iframes somewhere on the page (either on their window, document or dom elements).代码可能会或可能不会为它自己的自定义事件之一添加到外部页面上的任何元素或页面上某处的 iframe 之一(在它们的窗口、文档或 dom 元素上)的侦听器。
I know the name of the custom event, but how can I tell where the listener has been added?我知道自定义事件的名称,但我如何知道监听器被添加到哪里了?
Here's one option - override the standard implementation:这是一种选择 - 覆盖标准实现:
var addEventListenerImplementation = Node.prototype.addEventListener; Node.prototype.addEventListener = function (event, callback) { alert("Hey, someone attached an event handler to me"); addEventListenerImplementation.call(this, event, callback); }; document.getElementById("div").addEventListener("click", function () { alert("clicked"); });
div { background: red; width: 300px; height: 300px; }
<div id="div"/>
This should work in most cases but unfortunately addEventListener
isn't the only way to attach events so you might need to also override Event.prototype.observe
.这在大多数情况下应该有效,但不幸的是addEventListener
不是附加事件的唯一方法,因此您可能还需要覆盖Event.prototype.observe
。 Lastly, if the event handler is attached using element.onclick
or any other onevent
function you can't really override them.最后,如果事件处理程序是使用element.onclick
或任何其他onevent
函数附加的,则您无法真正覆盖它们。 One possible though super-messy solution would be the following:一种可能但超级凌乱的解决方案如下:
Node.prototype
.在Node.prototype
上定义一个新属性。 Object.defineProperty(Node.prototype, "ONMYCLICK", function () { get: function () { return null; }, set: function (handler) { console.log("Hey, a handler was attached!"); this.onclick = handler; } });
.onclick
with .ONMYCLICK
在您最喜欢的文本编辑器中打开库的脚本并将所有出现的.onclick
替换为.ONMYCLICK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.