如何使用JavaScript检测Ctrl + V,Ctrl + C?

时间:2010-05-25 11:07:29

标签: javascript jquery html

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

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

如何实现这一目标?

18 个答案:

答案 0 :(得分:162)

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

$(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");
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Ctrl+c Ctrl+v disabled</h3>
<textarea class="no-copy-paste"></textarea>
<br><br>
<h3>Ctrl+c Ctrl+v allowed</h3>
<textarea></textarea>

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

Codepen demo

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

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

答案 1 :(得分:50)

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

$("#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/

答案 2 :(得分:38)

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

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事件。我还将ctrlKey替换为metaKey替换为mac。

此方法的限制:

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

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

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

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

答案 3 :(得分:12)

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

正如你在我的其他答案中所见,拦截 Ctrl + v Ctrl + c 附带许多副作用,它仍然不会阻止用户使用Firefox Edit菜单等粘贴。

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以获取更多信息。

答案 4 :(得分:9)

现场演示: 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!');
        }
    });

}); 

答案 5 :(得分:8)

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

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

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

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

答案 6 :(得分:3)

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

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

答案 7 :(得分:3)

而不是onkeypress,请使用onkeydown。

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

答案 8 :(得分:2)

您可以使用此代码进行右键单击, CTRL + C CTRL + V CTRL + X 检测并阻止他们采取行动

$(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();
    });

答案 9 :(得分:1)

另一种方法(不需要插件)只使用传入的event objectctrlKey属性。它表示在此时是否按下 Ctrl 事件,像这样:

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

另见jquery: keypress, ctrl+c (or some combo like that)

答案 10 :(得分:0)

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

$('#<%= 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

答案 11 :(得分:0)

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

答案 12 :(得分:0)

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

答案 13 :(得分:0)

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

   $(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.
      } 
    }

答案 14 :(得分:0)

重要提示

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

因此,您应该使用e.key.toUpperCase().charCodeAt(0)而不是e.keyCode

答案 15 :(得分:0)

允许覆盖复制事件的钩子可以用于粘贴事件。输入元素无法显示:无;或可见性:隐藏;不幸的是

export const useOverrideCopy = () => {
  const [copyListenerEl, setCopyListenerEl] = React.useState(
    null as HTMLInputElement | null
  )
  const [, setCopyHandler] = React.useState<(e: ClipboardEvent) => void | null>(
    () => () => {}
  )
  // appends a input element to the DOM, that will be focused.
  // when using copy/paste etc, it will target focused elements
  React.useEffect(() => {
    const el = document.createElement("input")  
    // cannot focus a element that is not "visible" aka cannot use display: none or visibility: hidden
    el.style.width = "0"
    el.style.height = "0"
    el.style.opacity = "0"
    el.style.position = "fixed"
    el.style.top = "-20px"
    document.body.appendChild(el)
    setCopyListenerEl(el)
    return () => {
      document.body.removeChild(el)
    }
  }, [])
  // adds a event listener for copying, and removes the old one 
  const overrideCopy = (newOverrideAction: () => any) => {
    setCopyHandler((prevCopyHandler: (e: ClipboardEvent) => void) => {
      const copyHandler = (e: ClipboardEvent) => {
        e.preventDefault()
        newOverrideAction()
      }
      copyListenerEl?.removeEventListener("copy", prevCopyHandler)
      copyListenerEl?.addEventListener("copy", copyHandler)
      copyListenerEl?.focus() // when focused, all copy events will trigger listener above
      return copyHandler
    })
  }
  return { overrideCopy }
}

像这样使用:

const customCopyEvent = () => {
    console.log("doing something")
} 
const { overrideCopy } = useOverrideCopy()
overrideCopy(customCopyEvent)

每次调用overrideCopy都会重新聚焦并在复制时调用您的自定义事件。

答案 16 :(得分:-2)

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;
}

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

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

答案 17 :(得分:-3)

有一些方法可以阻止它。

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

一些例子(需要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;});

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

相关问题