I do not believe that 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 does not help.- Any property that you can check on an object can exist both in a genuine Event object and in any object other than an event.
- You might think that the prototype chain might be useful for defining this, but it has the same problem as # 2 (can be easily replicated).
- The
contructor property may seem promising, but you can do this:
function DummyEvent(){ this.constructor.toString = function(){ return "function MouseEvent() { [native code] }"; } }
The result is console.log(e.constructor) print "function MouseEvent() { [native code] }"
So, is there a βreliableβ way to determine if an object is an event? No.
Edit - Please note that all this does not matter if you want to prevent event spoofing, as you can easily create real events.
var evt = new Event('click'); var evt2 = document.createEvent('MouseEvents'); evt2.initMouseEvent('click', ...);
Edit2 - I created the jsFiddle test, trying to find a way to distinguish objects, but I have not found anything specific yet. Please note that I did not point out properties on DummyEvent , because they are obviously easily fake.
source share