如何检测键盘事件已经绑定?

时间:2011-12-15 02:12:34

标签: javascript javascript-events google-chrome-extension

我正在使用用户的密钥事件创建Chrome扩展程序。 但是我想提醒用户该元素是否已经绑定了键盘事件。

如何检测键事件是否已绑定?

1 个答案:

答案 0 :(得分:2)

这很棘手。实际情况是,您可以通过几种不同的方式绑定到HTMLElement的事件。我想最简单的绑定方式(并检查是否绑定了某些东西)将是这样的:

var ele = document.getElementById("yourDiv");
if (ele.onkeydown) {
  alert("onkeydown event is already bound");
}
else {
  ele.onkeydown = yourEventHandler;
}

问题是,正如本文评论部分所述,如果您无法在之前更改HTML元素的原型,那么就没有真正的方法可以检测addEventListener或attachEvent添加的事件与编程的javascript。事件受到约束。 (因此,在绑定事件之前,用户脚本无法真正更改原型,因为它在页面上的所有脚本之后运行)。但是,如果它是您自己的页面,并且您只是想监视这些事件更改。您可以通过执行以下操作将其破解为原型:

// cache the original event handler
HTMLAnchorElement.prototype.realAddEventListener = HTMLAnchorElement.prototype.addEventListener;

// now override it so you can add in your custom functionality
HTMLAnchorElement.prototype.addEventListener = function(a,b,c){
    this.realAddEventListener(a,b,c); 
    // do whatever you want to cache those listening functions, maybe shove them in an array
    // for the current object
    if (!this.listeners) {  
        this.listeners = new Array();
    }
    this.listeners.push({a : a, b : b , c : c});
};

// code here that adds an event handler
document.getElementById("txtField").addEventListener("keydown", function() {
  console.log("key down pressed"); 
});

// find the event listeners that are bound
var listeners = document.getElementById("pressed").listeners;

看,我在这里发现这个问题也涵盖了这个问题,并且其中的一些好答案还有很多深度:How to find event listeners on a DOM node when debugging or from the JavaScript code?