31

given a content editable div. How can I detect a paste event, prevent the paste from being inserted so can I can intercept and sanitize the paste to include text only?

I also don't want to lose focus after the paste + sanitize is complete.

Limon Monte
  • 44,025
  • 43
  • 163
  • 189
Rachela Meadows
  • 775
  • 2
  • 11
  • 19
  • 1
    What would be helpful would be a fund that captures the paste event before it occurs, sanitizes, and then injects the safe content into the content editable w/o losing the cursor position. Ideas? – Rachela Meadows Nov 19 '11 at 00:29
  • 1
    IE, Safari, and Chrome allow for accessing the data in the clipboard, but you'll have to come up with a huge-headache of a workaround for Firefox. Much easier, if it's feasible, would be to just allow the paste, and then sanitize the content of the entire element after the fact. Would that work? – sdleihssirhc Nov 19 '11 at 00:42
  • There's a hacky way to do this that I've posted before: http://stackoverflow.com/questions/2176861/javascript-get-clipboard-data-on-paste-event-cross-browser/2177059#2177059, http://stackoverflow.com/questions/4365833/how-can-i-get-the-text-that-is-going-to-be-pasted-in-my-html-text-editor/4365862#4365862 – Tim Down Nov 19 '11 at 15:20

1 Answers1

29

UPDATE:

All major browsers now give you access to the clipboard data in a paste event. See Nico Burns's answer for an example on newer browser and also check out Tim Down's answer if you need to support older browsers.


You can listen for the onPaste event on the div to detect the paste. If you just want to disable the paste you can call event.preventDefault() from that listener.

To capture the pasted content however is a little bit more difficult since the onPaste event does not give you access to the pasted content. The usual way to handle this is to do the following from the onPaste event handler:

  • create a dummy div and place it outside the window boundaries so it's not visible to visitors
  • move the focus to this div
  • call a sanitizer method using a setTimeout(sanitize, 0)

and from your sanitizing method:

  • find the dummy div and get it's contents
  • sanitize the HTML and remove the div
  • move the focus back to the original div
  • insert the sanitized content in the original div
Community
  • 1
  • 1
dcro
  • 12,054
  • 4
  • 62
  • 73
  • 2
    The `paste` event is too late to do this kind of redirect in some browsers, but the general idea works. – Tim Down Nov 19 '11 at 15:21
  • 3
    Here is another very popular solution that has been tested cross browser http://stackoverflow.com/questions/2176861/javascript-get-clipboard-data-on-paste-event-cross-browser – yoshyosh Oct 03 '13 at 21:58