views:

65

answers:

3

Is it possible to intercept and modify text that gets pasted into a textarea?

If intercepting isn't possible, can I modify it after being pasted? (Without modifying the already present text in the textarea.)

+1  A: 

Maybe intercept keypresses, to know when CTRL+C is pressed, cache current text, then at CTRL+C's keyup, check current value against cached one, with simple text processing you can know the new text, and do whatever you want with, and update accordingly.

aularon
I'm not certain this works with all browsers, but is definitely a better approach I think. http://api.jquery.com/keypress/
userx
A: 

The best way I know of how to do this is to wait for the content to the text field to be pasted then wait for a keyup or a keydown trigger. This is shown in the code below:

<script language="javascript">

function testfunction()
{

 // This function will execute whenever the content of 

}
</script>

<textarea onkeyup="testfunction()" onkeydown="testfunction()"></textarea>

If you want to monitor a textarea for any changes, the following code would do that. It checks the value of the textarea every 1/10th of a second for any updates.

<textarea id="testfield"></textarea>

<script language="javascript">

var textarea = document.getElementById('testfield');
var textval = '';

function monitor()
{

 if(textval != textarea.value)
 {

  textval = textarea.value;
  testfunction();

 }

 setTimeout('monitor()', 100);

}

function testfunction()
{

 // This function will get executed whenever the value of the text area is altered (at most within 1/10th of a second)

}

monitor();
</script>

In both cases, you can modify the value of the textarea when testfunction() then update the value of the textarea with the updated value.

Consider using "setTimeout(monitor, 100);" instead of "setTimeout('monitor()', 100);". Eval is evil :)
userx
+1  A: 

With jQuery:

    jQuery(function($){
      $('#your_element').bind('paste', function(event){
        event.preventDefault();
        var clipboardData = event.originalEvent.clipboardData.getData('text/plain');
        console.log(clipboardData);
      }); 
     }      
    });

Works in IE and Webkit. With Firefox you might have to use this:

http://intridea.com/2007/12/16/faking-onpaste-in-firefox?blog=company

Carlos
Actually the onpaste event worked in Gecko 1.9.0.19 (Camino 2.0.4). I think it has been introduced in Firefox 3, here's the mozilla page: https://developer.mozilla.org/en/DOM/element.onpaste There is, however, no good way to get the pasted data.
Georg
Ah, thanks didn't know that Firefox 3 implemented onpaste, but it sucks that you can't get to the data with it.
Carlos