I'm creating a Chrome extension using user's key event. But I want to alert to user if the element already has been bound to a keyboard event.
How do I detect if key event is already bound?
I'm creating a Chrome extension using user's key event. But I want to alert to user if the element already has been bound to a keyboard event.
How do I detect if key event is already bound?
This is tricky. The reality is, you can bind to an HTMLElement's event in quite a few different ways. I suppose the easiest way to bind (and check to see if something is bound) would be something like this:
var ele = document.getElementById("yourDiv");
if (ele.onkeydown) {
alert("onkeydown event is already bound");
}
else {
ele.onkeydown = yourEventHandler;
}
The problem is, as asked in the comment section to this post, there's no real way to detect events added by addEventListener or attachEvent with programattic javascript if you don't have the ability to change the prototype for the HTML elements before the events are bound. (So a userscript can't really change the prototypes before events are bound, because it's run after all the scripts on the page are). However, if it's your own page, and you're just wanting to monitor for these event changes. You can hack it into the prototype by doing something like this:
// 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;
Looking, I found this question here which also covers this exact issue, and some good answers in there go in to alot of depth: How to find event listeners on a DOM node when debugging or from the JavaScript code?