Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Ctrl+U using Javascript

I just want to disable Ctrl+U and Ctrl+C event. The primary purpose of doing this is, preventing users from downloading any image or copying content from my website easily i.e. pressing Ctrl+U for viewing my webpage's source code or pressing Ctrl+C for copying content directly from my webpage.

Currently, I am using this piece of code but it disables my entire keyboard

 <script>
    /*function check(e)
    {
    alert(e.keyCode);
    }*/
    document.onkeydown = function(e) {
            if (e.ctrlKey && (e.keyCode === 67 || e.keyCode === 86 || e.keyCode === 85 || e.keyCode === 117)) {//Alt+c, Alt+v will also be disabled sadly.
                alert('not allowed');
            }
            return false;
    };
    </script>
like image 650
Debakant Mohanty Avatar asked Dec 04 '13 10:12

Debakant Mohanty


People also ask

How to disable Ctrl c in JavaScript?

To disable "Ctrl + C" put this script. function keypressed() {;return false;}document.

How do I disable Ctrl key?

Steps to disable or enable Ctrl key shortcuts in CMD on Windows 10: Step 1: Open Command Prompt. Step 2: Right-tap the Title bar and choose Properties. Step 3: In Options, deselect or select Enable Ctrl key shortcuts and hit OK.


3 Answers

Your problem is the return statement.

Though I would suggest you use addEventListener and the like, this is a working copy of your code:

document.onkeydown = function(e) {
        if (e.ctrlKey && 
            (e.keyCode === 67 || 
             e.keyCode === 86 || 
             e.keyCode === 85 || 
             e.keyCode === 117)) {
            alert('not allowed');
            return false;
        } else {
            return true;
        }
};
like image 176
Zimzalabim Avatar answered Oct 07 '22 23:10

Zimzalabim


This is finally what I got to disable Ctrl+U:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
document.onkeydown = function(e) {
        if (e.ctrlKey && 
            (e.keyCode === 67 || 
             e.keyCode === 86 || 
             e.keyCode === 85 || 
             e.keyCode === 117)) {
            return false;
        } else {
            return true;
        }
};
$(document).keypress("u",function(e) {
  if(e.ctrlKey)
  {
return false;
}
else
{
return true;
}
});
</script>
like image 42
Debakant Mohanty Avatar answered Oct 07 '22 23:10

Debakant Mohanty


Its simple just use the following code it will disable only Ctrl+U while Ctrl+C, Ctrl+V, Ctrl+S etc will works fine:

<script>
document.onkeydown = function(e) {
        if (e.ctrlKey && 
            (e.keyCode === 85 )) {
            return false;
        }
};
</script>
like image 2
Murad Ali Avatar answered Oct 07 '22 22:10

Murad Ali