Skip to content

Instantly share code, notes, and snippets.

@cesarfigueroa
Created September 25, 2014 23:48
Show Gist options
  • Save cesarfigueroa/27d332384cad45217168 to your computer and use it in GitHub Desktop.
Save cesarfigueroa/27d332384cad45217168 to your computer and use it in GitHub Desktop.
Paste onto a [contenteditable] element as plain text
document.querySelector('[contenteditable]').addEventListener('paste', function (event) {
event.preventDefault();
document.execCommand('inserttext', false, event.clipboardData.getData('text/plain'));
});
@percy507
Copy link

@bttger
Copy link

bttger commented Aug 2, 2022

As @jp3492 has said, the execCommand API is deprecated. The following code works the same by just setting the inner text of the target element.

function pasteAsPlainText(event) {
  event.preventDefault();
  event.target.innerText = event.clipboardData.getData("text/plain");
}

@jhwheeler
Copy link

As @jp3492 has said, the execCommand API is deprecated. The following code works the same by just setting the inner text of the target element.

function pasteAsPlainText(event) {
  event.preventDefault();
  event.target.innerText = event.clipboardData.getData("text/plain");
}

This is fine if you want the clipboard text to replace everything inside the target element, but not if you want to preserve any content that may already be present in the target. For example, I am writing this message now, and if I were to paste some text after this paragraph, I would expect everything I've written up until now to be preserved; however, replacing the inner text would replace everything.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment