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

JavascriptJqueryHtml

Javascript Problem Overview


How to detect ctrl+v, ctrl+c using 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 to achieve this?

Javascript Solutions


Solution 1 - Javascript

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

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

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)

Solution 2 - Javascript

With jquery you can easy detect copy, paste, etc by binding the function:

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

Solution 3 - Javascript

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 e.g. c event after the Ctrl key is held down. I've also substituted ctrlKey with metaKey for macs.

Limitations of this method:

  • Opera doesn't allow disabling right click events

  • Drag and drop between browser windows can't be prevented as far as I know.

  • The edit->copy menu item in e.g. Firefox can still allow copy/pasting.

  • 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.

Solution 4 - Javascript

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.

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.

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.

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.

Solution 5 - Javascript

If you use the ctrlKey property, you don't need to maintain state.

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

Solution 6 - Javascript

Live Demo : 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!');
		}
	});
 
});	

Solution 7 - Javascript

Short solution for preventing user from using context menu, copy and cut in jQuery:

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

Also disabling text selection in CSS might come handy:

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

Solution 8 - Javascript

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:

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

See also jquery: keypress, ctrl+c (or some combo like that).

Solution 9 - Javascript

I wrote a jQuery plugin, which catches keystrokes. It can be used to enable multiple language script input in html forms without the OS (except the fonts). Its about 300 lines of code, maybe you like to take a look:

Generally, be careful with such kind of alterations. I wrote the plugin for a client because other solutions weren't available.

Solution 10 - Javascript

instead of onkeypress, use onkeydown.

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

Solution 11 - Javascript

You can use this code for rightclick, CTRL+C, CTRL+V, CTRL+X detect and prevent their action

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

Solution 12 - Javascript

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.
Best example for this is Chrome's Inspect Element function, this allows you to change the value-property of a field.

Solution 13 - Javascript

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.

Solution 14 - Javascript

If anyone is interested in a simple vanilla JavaScript approach, see below.

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

Solution 15 - Javascript

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

Solution 16 - Javascript

Important note

I was using e.keyCode for a while and i detected that when i press ctrl + ., This attribute returns a wrong number, 190, while the ascii code of . is 46!

So you should use e.key.toUpperCase().charCodeAt(0) instead of e.keyCode.

$(document).keydown(function(event) {
  let keyCode = e.key.toUpperCase().charCodeAt(0);
  
  ...
}

Solution 17 - Javascript

You can listen to the keypress event, and halt the default event (entering the text) if it matches the specific keycodes

Solution 18 - Javascript

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.

Some examples (require 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRamakrishnanView Question on Stackoverflow
Solution 1 - JavascriptjackocnrView Answer on Stackoverflow
Solution 2 - JavascriptChris AnderssonView Answer on Stackoverflow
Solution 3 - JavascriptcryoView Answer on Stackoverflow
Solution 4 - JavascriptcryoView Answer on Stackoverflow
Solution 5 - JavascriptCrashalotView Answer on Stackoverflow
Solution 6 - JavascriptAbdennour TOUMIView Answer on Stackoverflow
Solution 7 - JavascriptjendarybakView Answer on Stackoverflow
Solution 8 - JavascriptAbu GhufranView Answer on Stackoverflow
Solution 9 - JavascriptmikuView Answer on Stackoverflow
Solution 10 - JavascriptatiruzView Answer on Stackoverflow
Solution 11 - JavascriptVarun NahariaView Answer on Stackoverflow
Solution 12 - JavascriptBlueCactiView Answer on Stackoverflow
Solution 13 - JavascriptGabriel PeterssonView Answer on Stackoverflow
Solution 14 - JavascriptJoeyView Answer on Stackoverflow
Solution 15 - JavascriptAmr BadawyView Answer on Stackoverflow
Solution 16 - JavascriptAmir FoView Answer on Stackoverflow
Solution 17 - JavascriptbalooView Answer on Stackoverflow
Solution 18 - JavascriptGustavo CardosoView Answer on Stackoverflow