Tuesday, April 17, 2012

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


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.


Source: Tips4all

10 comments:

  1. 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)

    ReplyDelete
  2. 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.

    ReplyDelete
  3. There are some instances where there isn't any option but to intercept or disable copy and paste events, though it should be only used in select circumstances. For example, I was writing a Japanese input system in JavaScript, and cutting/pasting would've messed up the ranges.

    Please consider against using as an "anti-piracy" measure though - it'll annoy legitimate users and the determined will always find a way around it:

    function disableCopyPaste(elm) {
    // Disable cut/copy/paste key events
    elm.onkeydown = interceptKeys

    // Disable right click events
    elm.oncontextmenu = function() {
    return false
    }
    }

    function interceptKeys(evt) {
    evt = evt||window.event // IE support
    var c = evt.keyCode
    var ctrlDown = evt.ctrlKey||evt.metaKey // Mac support

    // Check for Alt+Gr (http://en.wikipedia.org/wiki/AltGr_key)
    if (ctrlDown && evt.altKey) return true

    // Check for ctrl+c, v and x
    else if (ctrlDown && c==67) return false // c
    else if (ctrlDown && c==86) return false // v
    else if (ctrlDown && c==88) return false // x

    // Otherwise allow
    return true
    }


    Limitations of this method:


    Opera doesn't allow disabling right click events
    Drag and drop between browser windows can't be prevented as far as I know.
    The edit->copy menu item in e.g. Firefox can still allow copy/pasting.
    There's also no guarantee that for people with different keyboard layouts/locales that copy/paste/cut are the same key codes (though layouts often just follow the same standard as English), but blanket "disable all control keys" mean that select all etc will also be disabled so I think that's a compromise which needs to be made.

    ReplyDelete
  4. 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 :-)

    ReplyDelete
  5. 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:


    http://miku.github.com/jquery-retype


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

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

    ReplyDelete
  7. 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

    ReplyDelete
  8. Why is everyone so down on this question? It's a good question. Most of the people that are inputting are not programmers. They are likely to paste absurd things into fields when they can. Of course it is ultimately up to the client and server code to handle this.

    People will continue to paste from Word documents into WYSWYG editors like CKeditor (which has a Paste from Word option that most people don't even use) and continue to wonder why their page looks terrible. So in some cases you might need to prevent a user from pasting.

    By the way, I pasted this here from Word ;)

    ReplyDelete
  9. 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);" />

    ReplyDelete
  10. 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.

    ReplyDelete