Can You Make A Textarea Which Doesn't Automatically Edit Your Text?
Solution 1:
You could try using a <pre>
element with the contenteditable="true"
attribute instead of a textarea
. This should theoretically preserve the input.
Edit I
You could intercept the onpaste
event and normalise all instances of \r\n
to \n
and then generate the checksum. The JavaScript might look like this:
var input_el = document.querySelector('.your-textarea');
input_el.onpaste = function(e){
typeof e !== 'undefined' && e.preventDefault();
var clipbd_data;
// handle IE edge caseif (window.clipboardData && window.clipboardData.getData) {
clipbd_data = window.clipboardData.getData('Text').replace(/\r\n/g, "\n").replace(/^(.*)\n*$/gm, "$1");
}
elseif (e.clipboardData && e.clipboardData.getData) {
clipbd_data = e.clipboardData.getData('text/plain').replace(/\r\n/g, "\n").replace(/^(.*)\n*$/gm, "$1");
}
else {
return; // functionality not supported
}
input_el.value = clipbd_data;
returnfalse;
};
Note: I have not tested this.
Edit II
Intercepting the copy event
First, add the following onclick
handler to the textarea:
<textareaclass="your-textarea"onfocus="this.select()"onclick="this.focus();this.select()"></textarea><!-- could optionally add ontouchstart="this.select()" for phones, if you need to -->
This is important, because we're intercepting the copy
event — it's not as though we can grab the exact data the user copied, because they haven't copied it yet, so we need to force the user to select all the text in the textarea
automatically so we can pass the whole contents of the textarea
to the clipboard (after normalisation). This should be what the user wants to do anyway, so it shouldn't present a usability problem...
Now, to intercept copy and add your own text:
var txt_area = document.querySelector('.your-textarea');
txt_area.addEventListener('copy', function(e){
// stop the normal copy behaviourtypeof e !== 'undefined' && e.preventDefault();
// get the contents of the textareavar txt_before = txt_area.value;
// normalisevar txt_after = txt_before.replace(/\r\n/g, "\n").replace(/^(.*)\n*$/gm, "$1");
e.clipboardData.setData('text/plain', txt_after);
});
Solution 2:
It looks like this may be impossible, so I am posting another question on using a different approach to getting data from javascript to a file without it being corrupted. See "Keep javascript blob from editing data when saving file"
Post a Comment for "Can You Make A Textarea Which Doesn't Automatically Edit Your Text?"