我可以删除Chrome扩展程序的事件监听器吗

我可以删除Chrome扩展程序的事件监听器吗

本文介绍了我可以删除Chrome扩展程序的事件监听器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Chrome的开发工具中,有一个可爱的界面,您可以在其中查看附加到给定DOM元素的所有事件侦听器,并根据您的需要删除其中任何一个。这是一个截图(增加了强调的箭头):

In Chrome's dev tools, there's a lovely interface where you can see all the event listeners attached to a given DOM element, and remove any of them as you see fit. Here's a screenshot (arrow added for emphasis):

我想编写一个Chrome扩展程序,可以自动从任何网页中删除事件监听器(我正在尝试编写Chrome扩展程序以禁用任何试图强制它的网站上的平滑滚动 - 我想删除'来自< body> 的轮子监听器是执行此操作的最直接途径。是否有任何JavaScript API可用于从Chrome扩展程序访问和修改此事件侦听器列表,还是仅限于开发工具GUI?

I'd like to write a Chrome extension that automatically removes event listeners from any web page (I'm trying to write a Chrome extension to disable smooth scrolling on any website that tries to force it upon you -- I figure removing the 'wheel' listener from <body> is the most direct route to do this). Is there any JavaScript API available for accessing and modifying this list of event listeners from a Chrome extension, or is it limited to the dev tools GUI?

要清楚,我了解,但该方法要求你有一个对原始监听器对象的引用 - 我没有这样的引用,所以该方法不适合我的目的。

To be clear, I'm aware of removeEventListener(), but that method requires that you have a reference to the original listener object -- I have no such reference, so that method won't suit my purposes.

推荐答案

当事件监听器在窗口(如你的问题中)或文件。为此,一种方法是大多数代码和库通常在冒泡阶段注册事件监听器,通过为 addEventListener的第三个 useCapture 参数传递false (或者根本不传递它)。由于捕获阶段首先发生,您可以通过注册停止进一步传播的捕获阶段侦听器来阻止调用事件侦听器。

eholder0's answer unfortunately doesn't help when the event listener is registered on window (like in your question) or document. For that, one way is that most code and libraries usually registers event listeners on the bubbling phase, by passing in false for the third useCapture parameter of addEventListener (or just not passing it in at all). Since the capturing phase happens first, you can prevent event listeners from being invoked by registering a capturing phase listener that stops further propagation.

例如,在某个代码审查站点上(以r开头并以eviewable.io结尾)删除了使用鼠标中键单击以通过文档上的mousedown事件滚动的功能,扩展内容脚本中的以下内容有效:

For example, on a certain code review site (starts with "r" and ends with "eviewable.io") that removes the ability to use the middle mouse button click for scrolling via a mousedown event on document, the following in an extension's content script works:

document.addEventListener("mousedown", function (event) {
    event.stopPropagation();
}, true);

注意第三个参数是 true 进行注册捕获阶段事件监听器。另请注意,它调用 event.preventDefault(),因此保留了浏览器内置的滚动功能。

Notice the third parameter is true to register a capturing phase event listener. Also notice that it does not call event.preventDefault(), so the browser's inbuilt scrolling function is retained.

这篇关于我可以删除Chrome扩展程序的事件监听器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:31