Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid WebKit contentEditable copy-paste resulting in unwanted CSS?

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?

like image 355
Martin Tajur Avatar asked Jul 22 '10 06:07

Martin Tajur


1 Answers

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.

like image 183
chiborg Avatar answered Sep 19 '22 16:09

chiborg