关于jquery:如何使用JavaScript检测Ctrl + V,Ctrl + C?

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

如何使用Javascript检测ctrl + vctrl + c

我需要限制粘贴在我的textareas中,最终用户不应该复制和粘贴内容,用户应该只在textarea中键入文本。

怎么做到这一点?


我出于兴趣而这样做了。我同意这不是正确的做法,但我认为这应该是op的决定......而且代码可以很容易地扩展到添加功能,而不是把它带走(比如更高级的剪贴板,或者Ctrl + s触发)服务器端保存)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$(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");
    });
});
1
2
3
4
5
6
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
Ctrl+c Ctrl+v disabled
<textarea class="no-copy-paste"></textarea>

Ctrl+c Ctrl+v allowed
<textarea></textarea>

另外,澄清一下,这个脚本需要jQuery库。

Codepen演示

编辑:删除3条冗余线(涉及e.which)感谢Tim Down的建议(见评论)

编辑:添加了对Mac的支持(cmd键而不是ctrl)


使用jquery,您可以通过绑定函数轻松检测复制,粘贴等:

1
2
3
4
5
6
7
8
9
$("#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!')
});

更多信息请访问:http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/


虽然在用作反盗版措施时可能会很烦人,但我可以看到可能存在一些合法的情况,因此:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
}

我使用event.ctrlKey而不是像在Mac OS X上的大多数浏览器那样检查密钥代码Ctrl / Alt"down"和"up"事件从未被触发,因此检测的唯一方法是使用event.ctrlKey例如按住Ctrl键后的c事件。我还用metaKey替换ctrlKey代替mac。

此方法的局限性:

  • Opera不允许禁用右键单击事件

  • 据我所知,无法阻止浏览器窗口之间的拖放。

  • 例如,edit - > copy菜单项Firefox仍然可以允许复制/粘贴。

  • 也不能保证对于具有不同键盘布局/区域设置的人来说,复制/粘贴/剪切是相同的密钥代码(尽管布局通常只遵循与英语相同的标准),但是"禁用所有控制键"意味着选择所有等也将被禁用,所以我认为这是一个需要做出的妥协。

还有另一种方法:在IE,Firefox,Chrome,Safari(有一些小问题)中可以注册和取消onpasteoncopyoncut事件,这是唯一不允许取消这些事件的主要浏览器事件是歌剧。

你可以在我的另一个答案中看到拦截Ctrl + vCtrl + c带来了许多副作用,它仍然不会阻止用户使用Firefox edit菜单粘贴等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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仍然存在一些使用此方法的小问题(当防止默认时,它会清除剪贴板而不是剪切/复制)但是现在Chrome中已经修复了该错误。

另请参阅:http://www.quirksmode.org/dom/events/cutcopypaste.html以及相关的测试页面http://www.quirksmode.org/dom/events/tests/cutcopypaste.html以获取更多信息。


现场演示:
http://jsfiddle.net/abdennour/ba54W/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(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!');
        }
    });

});

防止用户使用上下文菜单,复制和剪切jQuery的简短解决方案:

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

同样禁用CSS中的文本选择可能会派上用场:

1
2
3
4
5
6
7
8
.noselect {  
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
     user-select: none;
}


而不是onkeypress,使用onkeydown。

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

我写了一个jQuery插件,它可以捕获击键。它可用于在没有OS的情况下以html形式启用多语言脚本输入(字体除外)。它的大约300行代码,也许你想看看:

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

一般来说,要小心这种改动。我为客户编写了插件,因为其他解决方案不可用。


您可以使用此代码进行右键单击,CTRL + CCTRL + VCTRL + X检测并阻止其操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(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();
    });

另一种方法(不需要插件)只使用传入的事件对象的ctrlKey属性。它表示在事件发生时是否按下了Ctrl,如下所示:

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

另请参阅jquery:keypress,ctrl + c(或类似的一些组合)。


不要忘记,虽然您可能能够检测并阻止Ctrl + C / V,但您仍然可以更改某个字段的值。
最好的例子是Chrome的Inspect Element功能,它允许您更改字段的value-property。


重要的提示

我正在使用e.keyCode一段时间,我检测到当我按ctrl + .时,此属性返回错误的数字190,而.的ascii代码为46!

所以你应该使用e.key.toUpperCase().charCodeAt(0)而不是e.keyCode


您可以收听按键事件,并在与特定键码匹配时暂停默认事件(输入文本)


我已经有你的问题,我通过以下代码解决了..只接受数字

1
2
3
4
5
6
7
8
$('#<%= 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;
            }
        });

你可以检测到Ctrl id e.which == 17


如果使用ctrlKey属性,则无需维护状态。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
   $(document).keydown(function(event) {
      // Ctrl+C or Cmd+C pressed?
      if ((event.ctrlKey || event.metaKey) && event.keyCode == 67) {
         // Do stuff.
      }

      // Ctrl+V or Cmd+V pressed?
      if ((event.ctrlKey || event.metaKey) && event.keyCode == 86) {
         // Do stuff.
      }

      // Ctrl+X or Cmd+X pressed?
      if ((event.ctrlKey || event.metaKey) && event.keyCode == 88) {
         // Do stuff.
      }
    }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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;
}

现在,要在您希望限制的文本框中引用这些方法:

1
<input name="txtTest" id="txtTest" type="textbox" onmousedown="javascript:return noCopyMouse(event);" onkeykown="javascript:return noCopyKey(event);"  />


有一些方法可以防止它。

但是,用户将始终能够关闭javascript或只查看页面的源代码。

一些例子(需要jQuery)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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;});

编辑:Tim Down如何说,这个功能都是浏览器家属。