简体   繁体   English

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

[英]How to detect Ctrl+V, Ctrl+C using JavaScript?

How to detect Ctrl + V , Ctrl + C using JavaScript?如何检测Ctrl + VCtrl + C使用 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 can I achieve this?我怎样才能做到这一点?

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).我同意这不是正确的做法,但我认为这应该是操作员的决定......此外,代码可以轻松扩展以添加功能,而不是将其删除(例如更高级的剪贴板,或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>

Also just to clarify, this script requires the jQuery library.也只是为了澄清,这个脚本需要 jQuery 库。

Codepen demo代码笔演示

EDIT: removed 3 redundant lines (involving e.which) thanks to Tim Down's suggestion (see comments)编辑:由于 Tim Down 的建议,删除了 3 条冗余行(涉及 e.which)(见评论)

EDIT: added support for Macs ( cmd key instead of ctrl )编辑:添加了对 Mac 的支持( cmd键而不是ctrl

With jquery you can easy detect copy, paste, etc by binding the function:使用 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!')
});

More information here: http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/更多信息在这里: http : //www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/

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 eg c event after the Ctrl key is held down.我使用event.ctrlKey而不是像在 Mac OS X 上的大多数浏览器上那样检查关键代码Ctrl / Alt “向下”和“向上”事件永远不会被触发,因此检测的唯一方法是使用event.ctrlKey按住 Ctrl键后的 eg c 事件。 I've also substituted ctrlKey with metaKey for macs.我还用metaKey替换了ctrlKey

Limitations of this method:这种方法的局限性:

  • Opera doesn't allow disabling right click events Opera 不允许禁用右键单击事件

  • Drag and drop between browser windows can't be prevented as far as I know.据我所知,无法阻止浏览器窗口之间的拖放。

  • The edit -> copy menu item in eg Firefox can still allow copy/pasting.例如 Firefox 中的edit -> copy菜单项仍然可以允许复制/粘贴。

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

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.还有另一种方法: onpasteoncopyoncut事件可以在 IE、Firefox、Chrome、Safari 中注册和取消(有一些小问题),唯一不允许取消这些事件的主要浏览器是 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.正如您在我的其他答案中所看到的,拦截Ctrl + vCtrl + 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 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. Safari 使用这种方法仍然存在一些小问题(在阻止默认设置时它会清除剪贴板而不是剪切/复制),但该错误现在似乎已在 Chrome 中修复。

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.另请参阅: http : //www.quirksmode.org/dom/events/cutcopypaste.html和相关的测试页面http://www.quirksmode.org/dom/events/tests/cutcopypaste.html了解更多信息。

Live Demo : http://jsfiddle.net/abdennour/ba54W/现场演示: 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!');
        }
    });

}); 

Short solution for preventing user from using context menu, copy and cut in jQuery:防止用户在 jQuery 中使用上下文菜单、复制和剪切的简短解决方案:

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

Also disabling text selection in CSS might come handy:在 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;
}

If you use the ctrlKey property, you don't need to maintain state.如果使用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.
      } 
    }

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

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

See also jquery: keypress, ctrl+c (or some combo like that) .另请参阅jquery: keypress, ctrl+c (或一些类似的组合)

而不是onkeypress,使用onkeydown。

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

I wrote a jQuery plugin, which catches keystrokes.我写了一个 jQuery 插件,它可以捕捉击键。 It can be used to enable multiple language script input in html forms without the OS (except the fonts).它可用于在没有操作系统的情况下以 html 形式启用多语言脚本输入(字体除外)。 Its about 300 lines of code, maybe you like to take a look:大概300行代码,也许你喜欢看:

Generally, be careful with such kind of alterations.通常,要小心此类更改。 I wrote the plugin for a client because other solutions weren't available.我为客户编写了插件,因为其他解决方案不可用。

You can use this code for rightclick, CTRL + C , CTRL + V , CTRL + X detect and prevent their action您可以将此代码用于右键单击、 CTRL + CCTRL + VCTRL + 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();
    });

Another simple way using Jquery:另一种使用 Jquery 的简单方法:

$(document).keydown( function(e)
{
    if (e.ctrlKey && e.key == 'c')
    {
        console.log('got ctrl c');
    }
    else if (e.ctrlKey && e.key == 'v')
    {
        console.log('got ctrl v');
    }
});

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.不要忘记,虽然您可能能够检测并阻止Ctrl + C / V ,但您仍然可以更改某个字段的值。
Best example for this is Chrome's Inspect Element function, this allows you to change the value-property of a field.最好的例子是 Chrome 的 Inspect Element 功能,它允许您更改字段的值属性。

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你可以检测Ctrl id e.which == 17

A hook that allows for overriding copy events, could be used for doing the same with paste events.允许覆盖复制事件的钩子可用于对粘贴事件执行相同的操作。 The input element cannot be display: none;输入元素不能显示:无; or visibility: hidden;或可见性:隐藏; sadly可悲的是

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

Used like this:像这样使用:

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

Every time you call overrideCopy it will refocus and call your custom event on copy.每次您调用 overrideCopy 时,它都会重新聚焦并在复制时调用您的自定义事件。

If anyone is interested in a simple vanilla JavaScript approach, see below.如果有人对简单的原生 JavaScript 方法感兴趣,请参见下文。

      let ctrlActive = false;
      let cActive = false;
      let vActive = false

      document.body.addEventListener('keyup', event => {
        if (event.key == 'Control') ctrlActive = false;
        if (event.code == 'KeyC') cActive = false;
        if (event.code == 'KeyV') vActive = false;
      })

      document.body.addEventListener('keydown', event => {
        if (event.key == 'Control') ctrlActive = true;
        if (ctrlActive == true && event.code == 'KeyC') {

          // this disables the browsers default copy functionality
          event.preventDefault()

          // perform desired action(s) here...
          console.log('The CTRL key and the C key are being pressed simultaneously.')

        }

        if (ctrlActive == true && event.code == 'KeyV') {

          // this disables the browsers default paste functionality
          event.preventDefault()

          // perform desired action(s) here...
          console.log('The CTRL key and the V key are being pressed simultaneously.')

        }

      })

The code above would disable the default copy in the browser.上面的代码将禁用浏览器中的默认copy If you'd like keep the copy functionality in the browser, just comment out this bit: event.preventDefault() and you can then run any desired actions while allowing the user to copy content.如果您想在浏览器中保留复制功能,只需注释掉这一位: event.preventDefault() ,然后您可以在允许用户复制内容的同时运行任何所需的操作。

element.addEventListener('keydown', function (e) {
    if (e.key == 'c' && e.ctrlKey) {
        e.preventDefault(); // prevent from copying
    }
    if (e.key == 'v' && e.ctrlKey) {
        e.preventDefault(); // prevent from pasting
    }
}

您可以监听 keypress 事件,如果它与特定的键码匹配,则停止默认事件(输入文本)

Important note重要的提示

I was using e.keyCode for a while and i detected that when i press ctrl + .我使用e.keyCode有一段时间了,当我按下ctrl + 时我发现了这一点 , This attribute returns a wrong number, 190, while the ascii code of . , 该属性返回错误的数字 190,而. is 46!是46!

So you should use e.key.toUpperCase().charCodeAt(0) instead of e.keyCode .所以你应该使用e.key.toUpperCase().charCodeAt(0)而不是e.keyCode

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

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.但是,用户始终可以关闭 javascript或仅查看页面的源代码。

Some examples (require jQuery)一些示例(需要 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.编辑:Tim Down 怎么说,这些功能都依赖于浏览器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM