Remove Styles from Text when Copying / Cutting using CSS or Javascript

Mojowen picture Mojowen · Sep 16, 2011 · Viewed 7.3k times · Source

Yo,

Alright been noodling on this one for a while: How copy/cut styled text without bringing along any style baggage (background-color, color, etc)?

Couple of routes of attacks that have been foiled:

  1. Style the text differently using ::select? Doesn't work, ::style isn't copied
  2. Style the selected text using jQuery's select binding This only works for inputs, not p, divs
  3. Intercept and remove style by binding an event to copy/paste using jQuery? Can't access the copied object to remove stuff, tried using e.preventDefault(); then returning the event object but that didn't work either
  4. Modify the clipboard data once it's been saved? Also no dice, most browsers wont let you into this without flash and some sort confirmation

Anyway, thoughts? Seems like it would be very useful for sites that have white background colors.

Answer

Laizer picture Laizer · May 15, 2019

Given current browser capabilities, you can intercept the copy event, get the selection without style, and put that into the clipboard.

I've tested this code with Chrome/Safari/Firefox. Believe is should work on MS browsers as well.

document.addEventListener('copy', function(e) {
  const text_only = document.getSelection().toString();
  const clipdata = e.clipboardData || window.clipboardData;  
  clipdata.setData('text/plain', text_only);
  clipdata.setData('text/html', text_only);
  e.preventDefault();
});