9

I have a <div> that has contentEditable="true".

When I copy-paste content within the editable div, the pasted text gets wrapped into a lot of unwanted CSS.

For example, this: <p>text text</p> becomes:

<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; border-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; outline-width: 0px; outline-style: initial; outline-color: initial; font-size: 17px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; ">text text</p>

I understand the browser (Google Chrome in the current case) tries to be smart and all, but what I end up is completely irrelevant and unwanted CSS.

Is there any way to tell the WebKit-based browser not to generate this?

Martin Tajur
  • 5,242
  • 1
  • 20
  • 15

1 Answers1

8

I had the same problem, plus the problem that every browser creates different HTML. So I wrote a JavaScript port of the Sanitize library: Sanitize.js

Sanitize.js is a whitelist-based HTML sanitizer written in JavaScript. Given a list of acceptable elements and attributes, Sanitize.js will remove all unacceptable HTML from a DOM node.

Have a look at the example, where I capture the paste event and process the HTML afterwards.

chiborg
  • 26,978
  • 14
  • 97
  • 115
  • Thanks. I actually ended up using a similar sanitizer in the back-end (using PHP Tidy) to remove unwanted markup before storing the input in the database. – Martin Tajur Sep 03 '10 at 07:37
  • 1
    Few years gone by and I have moved away from PHP Tidy. In fact, I am using the exact same library (Sanitize.js) now and highly recommend it! Works nicely with JSDom on NodeJS as well. – Martin Tajur Apr 25 '12 at 07:47
  • Your Sanitize library is awesome! Thanks for that mate. – Rijk Apr 16 '13 at 09:13