I'm using angular 4 and trying to work with on contenteditable
<div contenteditable='true' id='editor' [innerHtml]='data'></div>
I need to detect paste event and then manipulate the data to remove all the inline css and HTMl tag other than bold, italics, and para and then paste it as normal text.
I have successfully detected the paste event by
document.getElementById('editor').addEventListener('paste', handlePaste);
function handlePaste(e) {
var clipboardData, pastedData;
// Stop data actually being pasted into div
clipboardData = e.clipboardData;
pastedData = clipboardData.getData('text/html');
e.stopPropagation();
e.preventDefault();
}
I'm able to manipulate the pastedData but not able to initiate the paste behaviour. Using preventDefault and stopPropagation I'm able to stop the default behaviour of paste, and also using getData I'm able to extract the data from clipboard. But now I'm stuck here, I'm not able to initiate paste event. In the docs it is said that we need to create a custom event like pasteClipboardData(newData). But I could find any reference on how to create such event.
// Since we are canceling the paste operation, we need to manually
// paste the data into the document.
pasteClipboardData(newData);
You don't need to dispatch another paste
event. Just insert the content you want into the contenteditable
.
Here's an example using document.execCommand("insertHTML", ...)
- see other questions (like this one) to make it work in IE:
window.onload = function() {
document.addEventListener('paste', function(e){
console.log("paste handler");
var s = e.clipboardData.getData('text/html').replace("this", "that")
document.execCommand("insertHTML", false, s);
e.preventDefault();
});
}
<html>
<p>1) copy <b>this</b> text</p>
<div contenteditable id="target">
<p>2) paste it here: ... ('this' should be replaced by 'that')</p>
</div>
Related: overriding the copy
event.