How to detect Ctrl+V, Ctrl+C using JavaScript?

2019-01-01 00:08发布

问题:

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

How to achieve this?

回答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,
        ctrlKey = 17,
        cmdKey = 91,
        vKey = 86,
        cKey = 67;

    $(document).keydown(function(e) {
        if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;
    }).keyup(function(e) {
        if (e.keyCode == ctrlKey || e.keyCode == cmdKey) 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.

Codepen demo

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

EDIT: added support for Macs (cmd key instead of ctrl)



回答2:

With jquery you can easy detect copy, paste, etc by binding the function:

$(\"#textA\").bind(\'copy\', function() {
    $(\'span\').text(\'copy behaviour detected!\')
}); 
$(\"#textA\").bind(\'paste\', function() {
    $(\'span\').text(\'paste behaviour detected!\')
}); 
$(\"#textA\").bind(\'cut\', function() {
    $(\'span\').text(\'cut behaviour detected!\')
});

More information here: http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/



回答3:

While it can be annoying when used as an anti-piracy measure, I can see there might be some instances where it\'d be legitimate, so:

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
}

I\'ve used event.ctrlKey rather than checking for the key code as on most browsers on Mac OS X 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. I\'ve also substituted ctrlKey with metaKey for macs.

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.


回答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.



回答5:

Live Demo : http://jsfiddle.net/abdennour/ba54W/

$(document).ready(function() {

    $(\"#textA\").bind({
        copy : function(){
            $(\'span\').text(\'copy behaviour detected!\');
        },
        paste : function(){
            $(\'span\').text(\'paste behaviour detected!\');
        },
        cut : function(){
            $(\'span\').text(\'cut behaviour detected!\');
        }
    });

}); 


回答6:

Short solution for preventing user from using context menu, copy and cut in jQuery:

jQuery(document).bind(\"cut copy contextmenu\",function(e){
    e.preventDefault();
});

Also disabling text selection in CSS might come handy:

.noselect {  
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
     user-select: none;
}


回答7:

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.



回答8:

instead of onkeypress, use onkeydown.

<input type=\"text\" onkeydown=\"if(event.ctrlKey && event.keyCode==86){return false;}\" name=\"txt\">


回答9:

You can use this code for rightclick, CTRL+C, CTRL+V, CTRL+X detect and prevent their action

$(document).bind(\'copy\', function(e) {
        alert(\'Copy is not allowed !!!\');
        e.preventDefault();
    }); 
    $(document).bind(\'paste\', function() {
        alert(\'Paste is not allowed !!!\');
        e.preventDefault();
    }); 
    $(document).bind(\'cut\', function() {
        alert(\'Cut  is not allowed !!!\');
        e.preventDefault();
    });
    $(document).bind(\'contextmenu\', function(e) {
        alert(\'Right Click  is not allowed !!!\');
        e.preventDefault();
    });


回答10:

Another approach (no plugin needed) it to just use ctrlKey property of the event object that gets passed in. It indicates if Ctrl was pressed at the time of the event, like this:

$(document).keypress(\"c\",function(e) {
  if(e.ctrlKey)
    alert(\"Ctrl+C was pressed!!\");
});

See also jquery: keypress, ctrl+c (or some combo like that).



回答11:

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



回答12:

Don\'t forget that, while you might be able to detect and block Ctrl+C/V, you can still alter the value of a certain field.
Best example for this is Chrome\'s Inspect Element function, this allows you to change the value-property of a field.



回答13:

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



回答14:

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);\"  />


回答15:

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.