Sanitize insert using jquery in contentEditable div

I am trying to sanitize a paste in a contentEditable div. That is, the code should look something like this:

$('#content').bind('paste',function(e) { // Ensure pasted markup is valid }); 

Ideally, I could analyze the embedded text and reformat it in a way that is suitable for the site, but I do not know how to do it.

Alternatively, it would be convenient for me to embed text as plain text (as opposed to HTML), but I don't know how to do this.

I’m a little less pleased with the decision to have a window with a text field, asking the user to insert it in this text area and then place the text in the content at the previous cursor position. I know how to do this, but I want to avoid this.

And it’s completely inconvenient for me to simply prevent the user from inserting with e.preventDefault() .

Thanks in advance.

+4
source share
3 answers

Most browsers do not have direct access to access content inserted before it enters the DOM. There is, however, a rather complicated way to do this, which only works on pastes caused by the keyboard. See my answer here:

JavaScript gets clipboard data on paste (cross browser)

+2
source

I was able to achieve this using the rangy javascript library, which allowed me to save and restore the carriage position after disinfecting the contents.

https://github.com/timdown/rangy

Tested in Chrome and Safari.

 $("#content").on('paste', function(){ sanitize(); }); function sanitize(){ setTimeout(function(){ var savedSelection = rangy.saveSelection(); $("#content *").removeAttr("style"); // Do your parsing here. rangy.restoreSelection(savedSelection); }, 0); } 
+2
source

Could you check the content if it is already in the field, how to do it? Let the content be inserted, first save the original content, and if the new content is invalid, replace it with the old one. This is just a theory, but now I just have to experiment.

-1
source

All Articles