Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sanitizing paste event using jQuery in contentEditable div

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

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

Ideally, I would be able to parse through the pasted text and re-format it in a way that is appropriate to the site, but I don't know how to do this.

Alternatively, I would be comfortable pasting as plain text (as opposed to HTML), but I don't know how to do this either.

I am slightly less comfortable with the solution of having a box pop up with a textarea, asking the user to paste into this text area and then putting the text into the content at the previous cursor position. I know how to do this, but want to avoid it.

And I am completely uncomfortable with just preventing the user from pasting by using e.preventDefault().

like image 876
Deets McGeets Avatar asked Oct 09 '22 22:10

Deets McGeets


2 Answers

There is no direct way in most browsers to access the content pasted before it goes into the DOM. There is, however, a fairly elaborate way to do this that only works for pastes triggered by the keyboard. See my answer here:

JavaScript get clipboard data on paste event (Cross browser)

like image 185
Tim Down Avatar answered Oct 12 '22 13:10

Tim Down


I've been able to achieve this with the rangy javascript library allowing me to save and restore the caret position after sanitizing the content.

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);  
}
like image 27
Etienne Martin Avatar answered Oct 12 '22 11:10

Etienne Martin