捕获给定类型的 *所有* 事件,无论 bubble/target
Capture *all* events of a given type, regardless of bubble/target
我正在编写一个 Chrome 扩展,需要通知 所有 click
和 keyup
事件,无论是否 stopPropagation
/etc 在消费代码中被调用。这意味着 document.addEventListener
不在 table.
我试过以下方法:
尝试 1:连接到 addEventListener
const _addEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(eventName, eventHandler) {
console.log('DOM Event', eventName);
_addEventListener.call(this, eventName, eventHandler);
};
尝试 2:连接到 stopPropagation
const _stopPropagation = Event.prototype.stopPropagation;
Event.prototype.stopPropagation = function() {
console.log('Stop Propagation:', this);
return _mouseEvent.apply(this, arguments);
};
尝试 3:挂钩偶数构造函数
const _mouseEvent = MouseEvent;
MouseEvent = function() {
console.log('Mouse Event:', this);
return _mouseEvent.apply(this, arguments);
};
const _keyboardEvent = KeyboardEvent;
KeyboardEvent = function() {
console.log('Keyboard Event:', this);
return _keyboardEvent.apply(this, arguments);
};
作为最后的手段,我可以在 每个 DOM 元素上添加我自己的 click
事件监听器——但这似乎是一个巨大的开销看起来应该可行的东西。
有人知道可行的选择吗?
哎呀,我不知道我怎么忘了useCapture
。这有效:
document.addEventListener('click', function() {}, true /* <--- this */);
我正在编写一个 Chrome 扩展,需要通知 所有 click
和 keyup
事件,无论是否 stopPropagation
/etc 在消费代码中被调用。这意味着 document.addEventListener
不在 table.
我试过以下方法:
尝试 1:连接到 addEventListener
const _addEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(eventName, eventHandler) {
console.log('DOM Event', eventName);
_addEventListener.call(this, eventName, eventHandler);
};
尝试 2:连接到 stopPropagation
const _stopPropagation = Event.prototype.stopPropagation;
Event.prototype.stopPropagation = function() {
console.log('Stop Propagation:', this);
return _mouseEvent.apply(this, arguments);
};
尝试 3:挂钩偶数构造函数
const _mouseEvent = MouseEvent;
MouseEvent = function() {
console.log('Mouse Event:', this);
return _mouseEvent.apply(this, arguments);
};
const _keyboardEvent = KeyboardEvent;
KeyboardEvent = function() {
console.log('Keyboard Event:', this);
return _keyboardEvent.apply(this, arguments);
};
作为最后的手段,我可以在 每个 DOM 元素上添加我自己的 click
事件监听器——但这似乎是一个巨大的开销看起来应该可行的东西。
有人知道可行的选择吗?
哎呀,我不知道我怎么忘了useCapture
。这有效:
document.addEventListener('click', function() {}, true /* <--- this */);