Don’t Embed Events in Markup

Many newer developers (or those trying to cut corners) tend to embed the JavaScript event handler directly in the markup of their application or site, such as:

<a href="javascript:void(0)" onclick="processForm();">Process Form</a>

While this may work perfectly fine in an unprotected environment, adding event handlers like this may cause Caja to strip them out of the final output in many containers or sites. Although restrictions are imposed on the server-side cajoler that runs when the code first loads, the client-side sanitizer that runs against code inserted after the initial load—such as through an innerHTML call—is much stricter about what code it allows through.

The practice of not embedding events in markup is especially valuable when you are obtaining content from another source, such as through an AJAX request, where that source has embedded JavaScript events, and then you attempt to load it into the existing content through an innerHTML call. In most instances, the client-side sanitizer will strip all JavaScript from the AJAX return value, leaving you with a nonfunctional node structure. In this case, once an AJAX request returns, you can immediately file off a function to assign click handlers to required DOM nodes.

There are a few methods you can employ to attach event handlers to DOM nodes. In Caja’s early days, when the onclick method was restricted, using addEventListener or attachEvent (depending on the browser) was one of the best options ...

Get Programming Social Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.