views:

674

answers:

9

How to detect ctrl+v ,Ctrl+c using Javascript?

i need to restrict pasting in my textareas,end user should not copy and paste the content, user should only type text in text area. how to achive this.

Thanks in advance.

A: 

You can listen to the keypress event, and halt the default event (entering the text) if it matches the specific keycodes

baloo
+4  A: 

Never do this. The world is lucky that it's difficult to do. It's the user's computer, and it is a security, choice and usability issue if you intrude into their choice. Go away.

Delan Azabani
+1 for that brief last sentence :)
alex
Perhaps it isn't the user's computer, but a computer that is used for taking tests or something. I don't understand why people get so stuck on what he's trying to achieve. If it happens to be a public site and people are restricted... then vote with you mouse button... leave the site.
Gert G
I disagree. It is the *developer's* software. And as such, it is his responsibility, to implement and expose its functionality in the best way possible. It is nothing but another flaw in the JavaScript API that this is not possible. It is a security, choice and usability issue, if you do not intrude into users choice, because frankly, 80% of all users prefer being guided, rather than spending their time RTFM. And an API should not dictate a developer, which users he targets. That's even worse than not providing the feature due to incompleteness.
back2dos
+2  A: 

I wrote a jQuery plugin, which catches keystrokes. It can be used to enable multiple language script input in html forms without the OS (except the fonts). Its about 300 lines of code, maybe you like to take a look:

Generally, be careful with such kind of alterations. I wrote the plugin for a client because other solutions weren't available.

The MYYN
A: 
function noCopyMouse(e) {
    if (event.button == 2 || event.button == 3) {
        alert('You are prompted to type this twice for a reason!');
        return false;
    }
    return true;
}

function noCopyKey(e) {
    var forbiddenKeys = new Array('c','x','v');
    var isCtrl;

        if(window.event) {
        if(window.event.ctrlKey)
            isCtrl = true;
        else
            isCtrl = false;
        }
        else {
                if(e.ctrlKey)
                    isCtrl = true;
                else
                    isCtrl = false;
        }

    if(isCtrl) {
        for(i=0; iif(forbiddenKeys[i] == String.fromCharCode(window.event.keyCode).toLowerCase()) {
                alert('You are prompted to type this twice for a reason!');
                return false;
            }
            }
    }
    return true;
}

And now to reference those methods in the textboxes that you wish to restrict:

<input name="txtTest" id="txtTest" type="textbox" onmousedown="javascript:return noCopyMouse(event);" onkeykown="javascript:return noCopyKey(event);"  />
Elangovan
Don't put `javascript:` at the start of event handler attributes. It serves no purpose and only works by coincidence. More importantly, this solution will not work: in `keydown` events, the `keyCode` property of the event is a key code rather than a character code, and they are not generally the same. Passing a key code to `String.fromCharCode` will have no meaning and will not do what you want.
Tim Down
Also, it almost goes without saying that this is a really bad thing to do, as mentioned by others here.
Tim Down
A: 

There is some ways to prevent it.

However the user will be always able to turn the javascript off or just look on the source code of the page.

Some examples (require jQuery)

/**
* Stop every keystroke with ctrl key pressed
*/
$(".textbox").keydown(function(){
    if (event.ctrlKey==true) {
        return false;
    }
});

/**
* Clear all data of clipboard on focus
*/
$(".textbox").focus(function(){
    if ( window.clipboardData ) {
        window.clipboardData.setData('text','');
    }
});

/**
* Block the paste event
*/
$(".textbox").bind('paste',function(e){return false;});

Edit: How Tim Down said, this functions are all browser dependents.

Gustavo Cardoso
This has a number of problems: first, it won't work in browsers that don't have a `paste` event, which includes all versions of Firefox prior to version 3. Second, `window.clipboardData` is IE only and I believe is now disabled by default in IE. Third, disabling all `keydown` events where the Ctrl key is pressed is excessive: you prevent useful keyboard shortcuts such as Ctrl-A (select all) and Ctrl-Z (undo). Fourth, as mentioned by others, this is a really bad thing to do.
Tim Down
You are right about that don't working on every browser. NobodyThe ctrl block is annoying indeed. It was handy once when a client wanted to block the "Confirmation Email and Password" field.
Gustavo Cardoso
+6  A: 

I just did this out of interest. I agree it's not the right thing to do, but I think it should be the op's decision... Also the code could easily be extended to add functionality, rather than take it away (like a more advanced clipboard, or Ctrl+s triggering a server-side save).

$(document).ready(function()
{
    var ctrlDown = false;
    var ctrlKey = 17, vKey = 86, cKey = 67;

    $(document).keydown(function(e)
    {
        if (e.keyCode == ctrlKey) ctrlDown = true;
    }).keyup(function(e)
    {
        if (e.keyCode == ctrlKey) ctrlDown = false;
    });

    $(".no-copy-paste").keydown(function(e)
    {
        if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)) return false;
    });
});

Also just to clarify, this script requires the jQuery library.

EDIT: removed 3 redundant lines (involving e.which) thanks to Tim Down's suggestion (see comments)

jackocnr
+1 I agree it should be the original poster's decision (though used sparingly), but bear in mind `AltGr` (`ctrl`+`alt` used on many European etc keyboards, see http://en.wikipedia.org/wiki/AltGr_key) to insert additional characters will be disabled. Maybe allow `alt` and `ctrl` at the same time but not `ctrl` by itself?
David Morrissey
Why the `keydown` and `keyup` handlers on `document`? You can test for the Ctrl key in the `$(".no-copy-paste").keydown` handler. Also, there's no need for the `e.keyCode || e.which` bit: `e.keyCode` works in all browsers that `e.which` works in, so `e.which` will never be used. Perhaps you were thinking of how you get a character code from a `keypress` event? Finally, this will do nothing about pastes from the context or edit menus, but I suppose the OP didn't ask directly about that.
Tim Down
also bear in mind that in most browsers on Mac OS X that `ctrl`/`alt` "down" and "up" events are *never* triggered, so the only way to detect is to use `event.ctrlKey` in the e.g. `c` event after the `ctrl` key is held down. Also make sure to substitute `ctrlKey` with `metaKey` on macs!
David Morrissey
@Tim: Ctrl key handlers on document to be general - as they may not want the ctrlDown variable to be exclusively linked to the no-copy-paste input(s). This is perhaps OTT. Thanks for the e.which tip - I've since spent half an hour researching the different use cases of e.keyCode and e.which with keydown() and keypress(), and what a mess (especially in firefox)!
jackocnr
although this answers the question on how to detect ctrl-c and ctrl-v, other ways of pasting (rightclick-paste) are not (yet) detected this way.
Konerak
jackocnr: I recommend Jan Wolter's JavaScript key handling article: http://unixpapa.com/js/key.html I've used it for reference many times and not found an error.
Tim Down
+2  A: 
David Morrissey
A: 

i already have your problem and i solved it by the following code .. that accept only numbers

$('#<%= mobileTextBox.ClientID %>').keydown(function(e) {
            ///// e.which Values
            // 8  : BackSpace , 46 : Delete , 37 : Left , 39 : Rigth , 144: Num Lock 
            if (e.which != 8 && e.which != 46 && e.which != 37 && e.which != 39 && e.which != 144
                && (e.which < 96 || e.which > 105 )) {
                return false;
            }
        });

you can detect ctrl id e.which == 17

Space Cracker
A: 

There's another way of doing this: onpaste, oncopy and oncut events can be registered and cancelled in IE, Firefox, Chrome, Safari (with some minor problems), the only major browser that doesn't allow cancelling these events is Opera.

As you can see in my other answer intercepting ctrl+v and ctrl+c comes with many side effects, and it still doesn't prevent users from pasting using the Firefox Edit menu etc.

function disable_cutcopypaste(e) {
    var fn = function(evt) {
        // IE-specific lines
        evt = evt||window.event
        evt.returnValue = false

        // Other browser support
        if (evt.preventDefault) 
            evt.preventDefault()
        return false
    }
    e.onbeforepaste = e.onbeforecopy = e.onbeforecut = fn
    e.onpaste = e.oncopy = e.oncut = fn
}

Safari still has some minor problems with this method (it clears the clipboard in place of cut/copy when preventing default) but that bug appears to have been fixed in Chrome now.

See also: http://www.quirksmode.org/dom/events/cutcopypaste.html and the associated test page http://www.quirksmode.org/dom/events/tests/cutcopypaste.html for more information.

Some good uses I can think of for this is for foreign language inputs (like onscreen keyboards, input methods for CJK languages), flashcards or kiosks as other users have noted.

Please treat your users with civility, and use it only for special cases :-)

David Morrissey