Reputation: 457
How can I let my users copy/cut styled text from my site, without bringing along any style baggage (background-color, color, etc)?
Routes of attacks that have been foiled:
Upvotes: 15
Views: 12820
Reputation: 6150
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();
});
Upvotes: 13
Reputation: 324607
I haven't got time to code up an example now, but you could do this for cut/copy triggered by keyboard shortcuts. It wouldn't work for cut/copy via context menu or Edit menu options because it relies on changing the user selection before the cut or copy event fires.
The steps:
window.getSelection().getRangeAt(0).cloneContents()
, although you'll need separate code for IE < 9 and you should check the selection is not collapsed.window.setTimeout()
that calls a function that removes the offscreen element and restores the original selection.Upvotes: 6
Reputation: 6276
Once you have triggered the copy or cut you can strip the html tags and only the text with some regex
var String = Sample.replace(/(<([^>]+)>)/ig,"");
Also if you have your stored text in a div with id "sample_div"
Use var String=$('sample_div').text('');
to get only the text inside
Upvotes: 0
Reputation: 34855
Do you need this to occur in the browser... for each user?
If not - and it is just for you - then you can do this with Clipmate software.
http://www.clipmate.com/index.htm
It has a feature that removes all styling.
Upvotes: -1