如何在 preventDefault 之后创建粘贴事件?

How to create a paste event after preventDefault?

我正在使用 angular 4 并尝试在 contenteditable

上工作
<div contenteditable='true' id='editor' [innerHtml]='data'></div>

我需要检测粘贴事件,然后处理数据以删除所有内联 css 和 HTMl 标记(粗体、斜体和段落除外),然后将其粘贴为普通文本。

我已通过

成功检测到粘贴事件
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();
}

我可以操作 pastedData 但无法启动粘贴行为。使用 preventDefault 和 stopPropagation 我能够停止粘贴的默认行为,并且使用 getData 我能够从剪贴板中提取数据。但现在我被困在这里,无法启动粘贴事件。在文档中说我们需要创建一个自定义事件,如 pasteClipboardData(newData)。但是我可以找到有关如何创建此类事件的任何参考。

// 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

您不需要发送另一个 paste 事件。只需将您想要的内容插入 contenteditable.

这是一个使用 document.execCommand("insertHTML", ...) 的示例 - 查看其他问题(如 this one)以使其在 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>

相关:.