Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 995
Mojowen Avatar asked Sep 16 '11 01:09

Mojowen


1 Answers

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();
});
like image 51
Laizer Avatar answered Sep 25 '22 05:09

Laizer