how to detect copy and paste in javascript?

前端 未结 2 677
醉酒成梦
醉酒成梦 2021-02-10 08:37

i have two field one is emailid and another is password in my form. i want to detect that when user reenter the email and password than he should not able to copy the above. he

相关标签:
2条回答
  • 2021-02-10 09:08

    You could disable ctrl+v combination and right click as well.

    for IE, you may tap into following event handlers:

    onpaste="return false;" 
    oncut="return false;" 
    oncontextmenu="return false;" 
    oncopy="return false;".
    

    Here is a workaround for all browsers:

    function noCTRL(e) {
          var code = (document.all) ? event.keyCode : e.which;
          var ctrl = (document.all) ? event.ctrlKey : e.modifiers & Event.CONTROL_MASK;
          var msg = "Sorry, this functionality is disabled.";
          if (document.all) {
            if (ctrl && code == 86) {
              //CTRL+V
              alert(msg);
              window.event.returnValue = false;
            } else if (ctrl && code == 67) { 
             //CTRL+C (Copy)
              alert(msg);
              window.event.returnValue = false;
            }
          } else {
            if (ctrl == 2) {
              //CTRL key
              alert(msg);
              return false;
            }
          }
        }
    

    In HTML section, your fields would look like:

    Email :<input name="email" type="text" value=""/><br/>
    Password :<input name="password" type="password" value=""/><br/>
    Confirm Email :<input name="email" type="text" value="" onkeydown="return noCTRL(event)"/>    
    Confirm Password :<input name="password" type="password" value="" onkeydown="return noCTRL(event)"/>
    

    I don't think user can copy password fields if input type is password

    Hope this helps.

    Note:

    1. Disabling JavaScript in browser will let users do whatever they want
    2. Always Keep this in mind: respect user's freedom.
    0 讨论(0)
  • 2021-02-10 09:23

    2020 update

    There are copy and paste events you can use to prevent these actions, or to modify the data being copied or pasted. (see the links for browser support)

    <input type="text" onpaste="return false">

    Or the longer javascript version:

    const elem = document.getElementById('nopaste');
    
    elem.addEventListener('paste', (event) => {
      event.preventDefault();
    });
    <input type="text" placeholder="can paste"><br>
    <input type="text" id="nopaste" placeholder="can not paste">

    0 讨论(0)
提交回复
热议问题