views:

237

answers:

1

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?

+1  A: 

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
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