From within a function like
function eventHandler(e) {
// ...
}
is there a reliable and efficient way to determine whether e
is a DOM event?
To check if an element is connected or attached to the DOM or the document object ( or otherwise called the context ), you can use the isConnected property in the element's object in JavaScript. The isConnected element property returns boolean true if it connected to the DOM ( document object) and false if not.
In this example, we have created empty Dom for output display. Using the new Event() method, the click event is passed as an object. Here, with the instanceof property, we identify that this object is an event. The next case passes a string value which comes up with an output that this object is not an event.
To check if an element has event listener on it with JavaScript, we can call the getEventListeners function in the Chrome developer console. getEventListeners(document. querySelector("your-element-selector")); in the Chrome developer console to select the element we want to check with querySelector .
Check the parentNode Property If it is, then we know the element is in the visible DOM. We just pass the div. parentNode property straight into the Boolean function to return true if it's truthy and false otherwise. And so we should see that the console log is true if we have the same HTML as in the first example.
I don't believe there is a reliable way to determine if a given object is NOT a DOM event.
typeof e
will always return 'object'
for genuine Event objects, which is not helpful.contructor
property might seem promising, but one could do this:function DummyEvent(){
this.constructor.toString = function(){
return "function MouseEvent() { [native code] }";
}
}
This ends up making console.log(e.constructor)
print "function MouseEvent() { [native code] }"
So, is there a "reliable" way to tell if an object is an event? No.
Edit — Note that all of this is irrelevant if you want to prevent event spoofing as you can create real events easily.
var evt = new Event('click');
var evt2 = document.createEvent('MouseEvents');
evt2.initMouseEvent('click', ...);
//etc
Edit2 — I've created a test jsFiddle trying to find some way to distinguish objects, but I haven't found anything definite yet. Note that I didn't bother to specify properties on the DummyEvent
because those can obviously easily be spoofed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With