Coding with Jesse

onAfterPaste

November 10th, 2005

Working with designMode="on" or contentEditable (what can we call this? I want to say Rich Text Editors or Midas Editors Web-Based HTML Editors or something. We don't really have a nice buzzword for this..), a common problem is dealing with pasted content. The user can paste any HTML into these areas, and more often than not, web applications don't want form elements or IFrames or other HTML included in the content.

It's not so difficult to process the innerHTML of a document to strip out bad HTML using regular expressions. The problem is, when can this cleaning happen?

Mozilla has no paste events at all. Internet Explorer has onBeforePaste and onPaste events, but no onAfterPaste. onPaste fires when the user pastes, but before the HTML actually goes into the editor. The idea is that the developer has a chance to look into the clipboard using window.clipboardData.getData(). Unfortunately, you can only retrieve the contents in URL or Text format, not HTML. Instead, it would be easier to allow the HTML to be pasted, then process the editor contents afterwards.

To accomplish this in Internet Explorer, we can simply set a timeout in the onPaste event. This works by allowing the browser time to finish its internal onPaste event before executing the code in the timeout. The onPaste event needs to be attached to the BODY of the editor IFrame using designMode, or the DIV element when using contentEditable.

function onPasteHandler(e) {
     setTimeout(function() {
          // editor cleaning code goes here
     }, 1); // 1ms should be enough
}

In Firefox, we can't use paste events. However, probably the best we can do is set a keypress handler and look for CTRL+V or SHIFT+INSERT and then do the same thing with a timeout. The keypress event handler needs to be attached to the document element in the IFrame.

function onKeyPressHandler(e) {
     if ((e.ctrlKey && e.keyCode == e.DOM_VK_V)
      || (e.shiftKey && e.keyCode == e.DOM_VK_INSERT)) {
          setTimeout(function() {
               // editor cleaning code goes here
          }, 1);
     }
}

This should only work with Mozilla/Firefox because e.DOM_VK_V and e.DOM_VK_INSERT are not defined in Internet Explorer.

Also note that there are still other ways to get HTML into the editor through Drag-and-Drop, or by using Edit>Paste on the Firefox menu. If you are serious about stripping HTML you will need to do it at other times as well. At least this way it will happen quickly enough that the editor won't misleadingly contain these elements, only to strip them out at an unpredictable time in the future.

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!