Remove Styles from Text when Copying / Cutting using CSS or Javascript
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:
- Handle the Ctrl-C and Ctrl-X keyboard shortcuts and the Mac equivalents.
- In this handler, create an off-screen element (absolute position and left -10000px, say) and copy the selected content into it. You can do this using
window.getSelection().getRangeAt(0).cloneContents()
, although you'll need separate code for IE < 9 and you should check the selection is not collapsed. - Do whatever you like to to change the styling of the content of the off-screen element.
- Move the selection to encompass the content of the off-screen element so that it is this content that is cut or copied.
- Add a brief delay (a few milliseconds) using to
window.setTimeout()
that calls a function that removes the offscreen element and restores the original selection.
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();
});