November 18, 2008

Generating events for fun and profit

Intro

It's not new or strange what this mini article is about - but since I had a hard time googling for it I thought why not writing some words about it. The DOM provides a set of methods to easily create and distribute events. That means you can simulate clicks or other events on arbitrary DOM elements for testing or even exploiting purposes.

Code

Let's have a look at the code that is necessary to generate a regular click in Firefox, Opera Webkit based browsers.

event = document.createEvent("Events");
event.initEvent('click', true, true);

document.dispatchEvent(event);

for(var i in event) {
alert(i + ' - ' + event[i]);
}

See - it's very easy. The MDC also provides some good documentation on methods like document.createEvent or document.dispatchEvent. Unfortunately this code won't work on IE - but there's an alternative using the proprietary method event.fireEvent.

Conclusion

Not much to say here - but what actually is weird is what you can see after iterating and echoing through the generated event object in Gecko based browsers. There's a whole bunch of quasi constants telling which events are available like with the other browsers - plus some extra stuff like TEXT or XFER_DONE. Safari and Chrome provide a property called clipboardData wrapped inside the event object - but it is set to undefined.

It doesn't seem to be be possible for any of the tested browsers to delegate events to off-domain resources - neither for popups, showModalDialog nor iframes.

Interesting is nevertheless that Firefox 3 allows to disable all system hot-keys on a specially crafted site using KeyEvents specified in DOM3. The user can neither save the site with Ctrl-S anymore, nor make a screen shot or turn to full screen. Hot-keys like Alt-F and Ctrl-T are disabled too of course.

<body onkeypress="alert(this.event);return false;"></body>
<script>
event = document.createEvent("KeyEvents");
event.initKeyEvent("keypress", true, true, null, true, false, false, false, 0, 0);
document.dispatchEvent(event);
</script>

Firefox and Webkit based browsers are the only one that support KeyEvents but Firefox is the only one that allows this kind of overriding - not even IE6 is that "cool". Safari 3.2 and the above listed code leads to a strange behavior on most test machines too - the browser skin simply turn black. The following code crashes Firefox 3.0.3 with latest Firebug installed - this combo doesn't seem ready for PopupBlockedEvents.

<script>
  event = document.createEvent("PopupBlockedEvents");
  console.dir(event)
</script>

Events are more than a wide sphere - and worth at least another article about oddities when coming to bubbling and capturing getting published the next days.