1

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

https://w3c.github.io/clipboard-apis/#override-paste

Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
  • You can create an (untrusted) paste event with `new ClipboardEvent()` ([spec](https://www.w3.org/TR/clipboard-apis/#dom-clipboardevent-clipboardevent)) and then fire it at the original event's target with `dispatchEvent` – Touffy Oct 09 '17 at 11:46
  • I have already tried it.. it's not working – Arghya Saha Oct 09 '17 at 12:41
  • Maybe because it's an untrusted event. You'll have to approach your problem from another angle then. [MutationObservers](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) are an effective way to deal with `contenteditable` elements. – Touffy Oct 09 '17 at 18:55

1 Answers1

2

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.

Nickolay
  • 31,095
  • 13
  • 107
  • 185