Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Created June 17, 2010 00:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nathansmith/441502 to your computer and use it in GitHub Desktop.
Save nathansmith/441502 to your computer and use it in GitHub Desktop.
Sanitize TinyMCE Content
//
// While TinyMCE can strip out <script> tags,
// it does not remove inline JS event handlers.
//
// Example: onmouseover, onclick, etc.
//
// This should be included at the bottom of a page,
// contained inside an <iframe> to sandbox user-created
// content. The reason it is contained in an <iframe>
// is to prevent user-created CSS from affecting
// the parent page's overall look and feel.
//
(function(d) {
var tags = d.body.getElementsByTagName('*');
var i = tags.length;
while (i--) {
var attr = tags[i].attributes;
var j = attr.length;
while (j--) {
if (attr[j].name.match(/^on/i)) {
tags[i][attr[j].name] = null;
}
}
if (tags[i].tagName.toLowerCase() === 'a' && tags[i].target !== '_blank') {
tags[i].target = '_top';
}
}
})(this.document);
@zackkitzmiller
Copy link

Wouldn't this be -insanely- slow?

@nathansmith
Copy link
Author

@zackkitzmiller

Yes — Possibly slow, depending on how much rich-text content the user had created.

Really, it should only be used within a sandboxed iframe, and on a preview page, when the user is checking to see what their rich-text output will look like.

Upon save, you'd of course want to do sanitation "for real" on the server-side.

Believe it or not, this was born of a Real World™ use case. Crazy, I know! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment