简体   繁体   English

阻止将新事件附加到元素

[英]Block new event from being attached to an element

I am binding event to an element. 我将事件绑定到元素。

How to prevent new JavaScript event to be bound to it? 如何防止新的JavaScript事件绑定到它?

I want to prevent unknown scripts to play with my elements. 我想防止未知脚本与我的元素一起玩。

You cannot block an unknown script from attaching an event listener to your object. 您不能阻止未知脚本将事件侦听器附加到对象。 The browser does not offer that feature. 浏览器不提供该功能。 The browser does block scripts that are running from other domains (other windows, tab, or frames) from messing with your DOM, but if a script is in the same domain or even in the same page, it is free to do whatever it wants to the DOM in that page. 浏览器确实阻止了从其他域(其他窗口,选项卡或框架)运行的脚本与您的DOM混乱,但是,如果脚本位于相同的域或同一页面中,则可以随意执行任何操作到该页面中的DOM。

If you have problems with unknown scripts doing bad things, then you're probably better off backing way, way up and describing what you're really trying to protect against because trying to block an event listener is like trying to keep someone out of one drawer when they're already roaming free through your house. 如果您遇到未知脚本执行不良操作的问题,那么最好采用后备方式,方式并描述您真正要保护的内容,因为尝试阻止事件侦听器就像是试图使某人与众不同当他们已经在您家中自由漫游时,请选择抽屉。 You probably need to secure things at a much higher level. 您可能需要在更高级别上保护事物。


If you want to get into the realm of "hacking" to try to block specific types of code, there are some options. 如果您想进入“黑客”领域来尝试阻止特定类型的代码,则有一些选择。 These aren't foolproof if the 3rd party code wants to get around them. 如果第三方代码想要绕过它们,这些并不是万无一失的。 In other words, these would be more useful if you can see what the 3rd party code does and it won't adapt itself to try to get around you: 换句话说,如果您能够看到第三方代码的功能,而又无法适应周围的情况,那么这些方法将更加有用:

Firstly, you can replace elem.addEventListener() after you've installed your event handler which will prevent other code from using elem.addEventListener() on that object again. 首先,您可以在安装事件处理程序后替换elem.addEventListener() ,这将防止其他代码再次在该对象上使用elem.addEventListener()

var item = document.getElementById("test");
item.addEventListener("click", function() {
    log("original event handler");
});

// install "do nothing" override method
item.oldAddEventListener = item.addEventListener;
item.addEventListener = function() {};

// this one will do nothing because addEventListener has been replaced
item.addEventListener("click", function() {
    log("2nd event handler");
});

Demo: http://jsfiddle.net/jfriend00/C5rzN/ 演示: http//jsfiddle.net/jfriend00/C5rzN/

This isn't foolproof as there are other ways to still install an event handler calling the method directly from the prototype or using the onclick property. 这不是万无一失的,因为还有其他方法可以安装直接从原型中或使用onclick属性调用该方法的事件处理程序。

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

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