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

前端 未结 17 2058
走了就别回头了
走了就别回头了 2020-11-22 13:47

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

I need to restrict pasting in my textareas, end user should not copy and p

17条回答
  •  臣服心动
    2020-11-22 14:42

    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;
        });
        
        // Document Ctrl + C/V 
        $(document).keydown(function(e) {
            if (ctrlDown && (e.keyCode == cKey)) console.log("Document catch Ctrl+C");
            if (ctrlDown && (e.keyCode == vKey)) console.log("Document catch Ctrl+V");
        });
    });
    
    

    Ctrl+c Ctrl+v disabled



    Ctrl+c Ctrl+v allowed

    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)

提交回复
热议问题