Explain Codes LogoExplain Codes Logo

Javascript trick for paste as plain text in execCommand

javascript
prompt-engineering
clipboard-api
execCommand
Alex KataevbyAlex KataevΒ·Feb 27, 2025
⚑TLDR

Short but sweet. Here's that tasty JavaScript snippet you need to get plain-text pasta 🍝:

// Listener of the year right here document.addEventListener('paste', function(e) { e.preventDefault(); // Stop! Paste-time! let text = e.clipboardData.getData('text/plain'); // Snag that plain text document.execCommand('insertText', false, text); // Unfunk the gunk and paste });

This commando snatches the pasta right from your clipboard, guard-checks if it's dressed too fancy (got formatting), and slips it into your HTML document neat and clean.

Checking browser support

Browsers are like snowflakes. ❄️ No two are exactly the same:

// Knock-knock. Who's there? document.queryCommandSupported! if (document.queryCommandSupported('insertText')) { // Party time! πŸŽ‰ } else { // Oops! Fallback plan needed. }

Make sure each has a beautiful fallback snowflake if needed!

When to call? Advanced scheduling

Custom event listeners

Gatecrashing the paste event:

  • Bouncer move: e.preventDefault() - not on the list, not coming in.
  • VIP pass: e.clipboardData.getData('text/plain') - come right in, we've been expecting you.
  • In IE’s afterparty, use window.clipboardData.
  • Welcome move: document.execCommand('insertHTML', false, text) or selection.createRange().pasteHTML(content).

Handling the outsiders

Older buddies not hip with insertText, remember them:

  • Call on range.deleteContents() and range.insertNode(document.createTextNode(text)) band for good music. 🎢
  • It's party time so maybe some timeout to enjoy.

Security bouncer

Pasta may be tasty 🍝 , but keep it clean for partygoers. Defence is the best offence against uninvited XSS attacks.

Taking it to the next level

Keyboard shortcuts & context menu

Making friends with keyboard and right-click menu, because Paste enjoys companions.

Compatibility dates

There's an audience to charm: IE11, Chrome, Firefox. Send invites via document.execCommand function and commands. Make a list, check it twice!

Stripping down the HTML

Quick wash and dry

Single line washer-dryer combo to get plain from HTML:

var plainText = clipboardData.getData('text/html').replace(/<[^>]*>/g, "");

Watching editable elements

Attach the listener to contenteditable="true" elements, because everyone loves plain-text pasta.

Checking the food

Making sure the pasta is cooked. Safe, performant and no HTML parasites.