JavaScript Trick For 'Paste as Plain Text' in Execcommand

Javascript trick for 'paste as plain text` in execCommand

It will intercept the paste event, cancel the paste, and manually insert the text representation of the clipboard:

http://jsfiddle.net/HBEzc/.
This should be the most reliable:

  • It catches all kinds of pasting (Ctrl+V, context menu, etc.)
  • It allows you to get the clipboard data directly as text, so you don't have to do ugly hacks to replace HTML.

I'm not sure of cross-browser support, though.

editor.addEventListener("paste", function(e) {
// cancel paste
e.preventDefault();

// get text representation of clipboard
var text = (e.originalEvent || e).clipboardData.getData('text/plain');

// insert text manually
document.execCommand("insertHTML", false, text);
});

How to keep line breaks on pasting with 'text/plain'?

Use the command insertText instead of the command insertHTML.

javascript how to paste as plain text in multiple fields or elements

document.querySelector yields one element. You want to use document.querySelectorAll to get all matching elements, and then iterate over that collection.

var editors = document.querySelectorAll('div[contenteditable]');
for(var i = 0, l = editors.length; i < l; i++) {
editors[i].addEventListener('paste', myCustomPasteFunction);
}

Fiddle

HTML text to plain text in Javascript without imports or npm installs

This is a non-deprecated deprecated tag. <xmp>

<xmp> is not an easy-to-find tag... I would recommend using it!

It says its deprecated if you search it online... but after using it in a live display it is definitely a working tag!

Inserting text with execCommand causes a duplication issue

I figured it out. Before you execute document.execCommand("insertHTML", false, "X");, check to see if the length of <span data-text="true"></span> is 0. If it is, just run document.execCommand("undo", false); following the insertHTML execCommand, and Voila! it works!

Here's the code:

if (document.querySelectorAll('span[data-text="true"]').length === 0) {
document.execCommand("insertHTML", false, "X");
document.execCommand("undo", false);
} else {
document.execCommand("insertHTML", false, "X");
}

It will check to see if you have entered the first character. If you did, it'll do the undo execCommand and remove the extra X. The else will just insertHTML since it won't insert any extras once characters have been entered.



Related Topics



Leave a reply



Submit