Javascript trick for paste as plain text
in execCommand
Short but sweet. Here's that tasty JavaScript snippet you need to get plain-text pasta π:
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:
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)
orselection.createRange().pasteHTML(content)
.
Handling the outsiders
Older buddies not hip with insertText
, remember them:
- Call on
range.deleteContents()
andrange.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:
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.
Was this article helpful?