0

I've read quite a few posts on here about how document.execCommand is being deprecated and that the Clipboard API should be used instead. However I can't figure out what to replace it with. I have a div[contenteditable] with auto-height and I want to convert pasted text into plain text when something is pasted into it. I know it may seem contradictive to use a rich-text element for plain text, but it's by far the best way to have a textarea autogrow that I've found. The following snippet does what I need it to, but again, since everybody is yelling don't use document.execCommand, what do you suggest I replace it with below? Thanks!

document.body.addEventListener("paste", function (e) {
    let pasteElements = ['SPAN', 'DIV', 'BR'];
    if (pasteElements.includes(e.target.nodeName)) {
        e.preventDefault();
        const text = e.clipboardData.getData('text/plain');
        document.execCommand("insertText", false, text.trim());
    }
});
SeaBass
  • 1,584
  • 4
  • 20
  • 46
  • You already seem to know the answer, use the Clipboard API. The question and [this MDN example](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API) cover your needs. – Rory McCrossan Oct 25 '22 at 08:06
  • Thanks! All I’m reading is copying, not pasting. I understand that the API can do both, but the reason for my post is, I don’t know how to use it :) Any leads to what snippet I need to replace this? `document.execCommand(”insertText”, false, text.trim());` – SeaBass Oct 25 '22 at 08:47
  • Look at the example in the MDN link :) – Rory McCrossan Oct 25 '22 at 09:01
  • @RoryMcCrossan But that appends to an element? What if I paste in the middle of a text? It also seems to complain and needing https to work. Guess I need to find a way to do that locally. Can we please open this thread again or find a different Stack Overflow post that actually is a duplicate. Thanks! – SeaBass Oct 25 '22 at 14:21
  • Then you would need to determine where the cursor is within the text and append the content at that location. The main point here is that there is no simple 'paste' logic in the clipboard API - you need to implement it however is required for your use case. – Rory McCrossan Oct 25 '22 at 14:22
  • Yes, I need it for my use case. I'll start a new thread where I emphasize that. Thanks – SeaBass Oct 25 '22 at 15:40

0 Answers0