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'));
});
@theharshin
Copy link

Works like charm! Thanks 👍

@jp3492
Copy link

jp3492 commented Dec 11, 2020

Since execCommand is discouraged to use as stated in the official MDN docs as well as w3school, I wonder if this is possible without execCommand. I need to figure this out for work and really cant come to a solution. I ultimately need to prevent formatted text to be pasted, with the cursor in the right place and no execCommand. Any ideas?

@eaydev
Copy link

eaydev commented Jun 15, 2021

You could always intercept the data and manually insert it as the innerText of the "content editable" element.

@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");
}

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