Disable ctrl + n and other ctrl + key combinations in JavaScript June 17, 2006

Posted by Slobodan Kovacevic in : Programming , trackback

Few days ago Vijay asked if there’s a way to disable ctrl + n combination (open the new window shortcut. So I set out to create a small Java Script that disables any ctrl + key combination (e.g. ctrl + v, ctrl + c, ctrl + a, etc.).

Script is a bit more complicated than Disable form submit on enter keypress and it should work in both Fire Fox and Internet Explorer.

<script language="JavaScript">
function disableCtrlKeyCombination(e)
{
        //list all CTRL + key combinations you want to disable
        var forbiddenKeys = new Array(‘a’, ‘n’, ‘c’, ‘x’, ‘v’, ‘j’);
        var key;
        var isCtrl;

        if(window.event)
        {
                key = window.event.keyCode;     //IE
                if(window.event.ctrlKey)
                        isCtrl = true;
                else
                        isCtrl = false;
        }
        else
        {
                key = e.which;     //firefox
                if(e.ctrlKey)
                        isCtrl = true;
                else
                        isCtrl = false;
        }

        //if ctrl is pressed check if other key is in forbidenKeys array
        if(isCtrl)
        {
                for(i=0; i<forbiddenkeys .length; i++)
                {
                        //case-insensitive comparation
                        if(forbiddenKeys[i].toLowerCase() == String.fromCharCode(key).toLowerCase())
                        {
                                alert(‘Key combination CTRL + ‘
                                        +String.fromCharCode(key)
                                        +‘ has been disabled.’);
                                return false;
                        }
                }
        }
        return true;
}
</script>

And you just add this to the field where you’d like to disable keys:

<input type="text" name="mytext"
        onKeyPress="return disableCtrlKeyCombination(event);"
        onKeyDown="return disableCtrlKeyCombination(event);" />

Although the key combinations are disabled only on one field the same script can be easily modified to disable ctrl + key combinations on whole page.

Also if you are looking for something more sophisticated and with more features you might want to take a look at a visitor comment that contains DisableKeys.js script that gives you more control and you can disable almost any key and/or key combination, including ctrl + key and alt + key.

Comments

1. pig - June 18, 2006

I wrote something very similar to this a couple of months ago, basically the same thing just a little more compact.

function disableCtrlModifer(evt)
{
var disabled = {a:0, c:0, x:0, v:0};
var ctrlMod = (window.event)? window.event.ctrlKey : evt.ctrlKey;
var key = (window.event)? window.event.keyCode : evt.which;
key = String.fromCharCode(key).toLowerCase();
return (ctrlMod && (key in disabled))? false : true;
}

2. Rhaine - July 15, 2006

where will you put this function? will you put it on onLoad for it wo work please reple…. tnx…

3. Rhaine - July 15, 2006

pig.. what is the complete script for this one? why does
the browser tell me the ctrlkey is not an object? i tried your script…
please elaborate.. thanks

4. Basti - July 17, 2006

@Rhaine - you don’t put these functions in onLoad. You put it in element in which you want to disable ctrl + key combinations. That might be a body tag (although I never tried it, but I presume it wouldn’t be a problem) or some text box. Either way you should make it look something like this:

<input type=“text” name=“mytext”
onKeyPress=“return disableCtrlKeyCombination(event);”
onKeyDown=“return disableCtrlKeyCombination(event);” />

5. carmella - July 22, 2006

A thousand thankyous Basti & pig! I searched for this on 7/21/2006 and see you posted yours just in the nick of time for me. It works great and by studying what you’ve done, I’ve learned some things. Thanks for taking the time to share what you’ve figured out with the rest of us.

6. sivabalan - August 21, 2006

can u explain me how to modify this script
fordisable ctrl + key combinations on whole page ?

7. garry loyder - August 23, 2006

it should work . did you even try this code?
do you have a working example? thanks.

8. webclown - October 18, 2006

I like the script it is eay to follow but how can I disable all keys except for the number keys
in the number pad or on the key board

9. Steve - December 8, 2006

QUOTE: “Although the key combinations are disabled only on one field the same script can be easily modified to disable ctrl + key combinations on whole page.”

For us beginners it would be handy if you told us how to do this. I want to protect the body text only on one particular page on my site

10. Omar - December 11, 2006

Steve,

You can do that by adding the function calls to the Body tag only:

11. Omar - December 11, 2006

Steve,

You can do that by adding the function calls to the Body tag only:

<body
onkeypress=”return disableCtrlKeyCombination(event);”
onkeydown=”return disableCtrlKeyCombination(event);” >

</body>

12. jordan - December 24, 2006

plz help me i need to disable ctrl alt delete …..does any one have any script for that???

13. Basti - December 24, 2006

@jordan - I am not sure if that’s possible. On most operating systems crtl+alt+delete have some special meaning and it just might be possible that you cannot override that using JavaScript.

If you happen to find a solution please let us know.

14. Stanislav - December 29, 2006

HEY
I was trying to disable CTRL + A….it works only in IE.
Do anybody have simple code wich works in Firefox 1.7
and any other browser
Help me please

15. Miguel Palizada - January 12, 2007

Does anybody knows how to clear the clipboard with javascript since firefox? The script is really amazing however Ctrl+C, Ctrl+Insert, Edit + Copy and mouse´s right click + copy is used to Copy and Ctrl+V, Shif+Insert, Edit + Paste and mouses´s rigth click + paste is used to Paste….. so, how can i prevent the Copy/Paste issue for all this combinations?

I´ll be gratefull if you can help me!!

16. Dev - January 17, 2007

Hello thank You very much for the Disable Ctrl + N code :)
Its just working GR8!!!

To go further on this, is there any way to disable the

” File > New > Window ” Option from Internet Explorer??

Thanks,
Dev

17. Slobodan Kovacevic - January 17, 2007

I am not sure that you can disable menu in IE, at least I never seen it. It would be strange for user if a Java Script would be able to block his menu options (for example, that would mean that you can block File -> Quit, so user cannot close the browser). Not to mention that this would be huge usability issue.

If you really need this perhaps you should try opening a page in a popup that doesn’t have menu at all.

18. Dev - January 17, 2007

hi,
i dnt know whether its the rite thread …
i want to disable (or customize) my browser(IE) Back button.
is there any way to trigger back button click event?
or is there any way to edit the history stack?
or is there any way to load a specific page always when
the back button is clickeD? lots of Questions for which i
searched a lot and couldnt find any answer yet… :(
any one pl help me..

thanks,
Dev

19. ja - January 17, 2007

i dnt think tht can be done dude.

20. JDROO - February 3, 2007

is there a way to disable them with html? im looking and can’t find a thing >.

21. Parker - March 3, 2007

Dev - to disable back button:

if (document.all) {
history.forward();
}
else {window.forward();
}

To trigger back button:

document.formName.buttonName.onClick = “if (document.all) {history.back();} else {window.back(); }”

To load a specific page when back button pressed, place this in a script in the of the page you are going back to:

if (history.next) {document.location=”http://defaultpage.htm”;}
}

although history.next does not work with FF

22. y0shi - March 21, 2007

works perfect! :) thanks alot

23. namrata - March 23, 2007

how to disable right click which invokes the contect menu?

24. Ram - April 12, 2007

This is very helpful. But, i need to disable the the Shift+PrintScreen in my webpage.
Because, it will avoid the user to copy the page (i.e. screenshots).

25. Slobodan Kovacevic - April 12, 2007

Ram I don’t think that’s possible. For example, on my Ubuntu (Linux) I can get a screen shot of my browser even though it’s not active window. In other words, I can get a screen shot regardless of what browser does.

26. Tarun - May 17, 2007

Thanks Slobodan …you saved a day

27. Tarun - May 17, 2007

RAM: “This is very helpful. But, i need to disable the the Shift+PrintScreen in my webpage.
Because, it will avoid the user to copy the page (i.e. screenshots).

You can use window.event.shiftKey for Internet Explorer

28. Can I hide URL in Javascript pop-up? - Articulate Community Forums - July 4, 2007

[…] Re: Can I hide URL in Javascript pop-up? Just curious–why do you want to hide the link? Also, not to ruin your day, but do a CTRL-N when your presentation opens. See how the presentation opens in a new window with full browser controls and the URL bar. So you probably want to do hide that also. I don’t recall this being brought up before so you may need to look elsewhere for possible answers. A Google search turned up this on disabling right-clicking in general on a page: Disabling right-click - JavaScript code And preventing CTRL-N: AS Workshop Disable ctrl + n and other ctrl + key combinations in JavaScript I’d get someone who knows JavaScript well and have them implement any solutions you find for you. (That’s experience talking from one who is not a programmer but who has fiddled with JS and messed some things up royally–good think I kept backups.) BTW, are all your learners on one browser or do they use various browsers and versions? Always simpler when you have just one browser to program around. Best! - Gerry […]

29. mukesh - July 11, 2007

i use this script in framset i not get result there is any other script r mothed to use in framset

30. John - July 18, 2007

Thx man, this works like a charm…..

31. vineet - July 23, 2007

hi i have written a html page like this, but it give me the error “object expected” when i try to press control key. Pls suggest me the answer for the same.

function disableCtrlKeyCombination(e)
{
//list all CTRL + key combinations you want to disable
var forbiddenKeys = new Array(‘a’, ‘n’, ‘c’, ‘x’, ‘v’, ‘j’);
var key;
var isCtrl;

if(window.event)
{

key = window.event.keyCode; //IE
if(window.event.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}
else
{
key = e.which; //firefox
if(e.ctrlKey)
isCtrl = true;
else
isCtrl = false;
}

//if ctrl is pressed check if other key is in forbidenKeys array
if(isCtrl)
{
for(i=0; i

hi how r u it?

32. Jaryd2006 - August 2, 2007

Hi im just wondering, Is it possible to use javascript to make like an onkeypress function to insert text like say a password into somewhere when I press like ctrl shift P or something? As in I press Ctrl shift P (or whatever else i choose) and it inserts my password into a box?

33. EsaS - August 5, 2007

to disable mouse and other key compination, just load page without properties, like above where url is called by this. openpage(”index.html”);
script in body tag. You also get more space to
show more on screen
function openapge(url){
var wid = screen.width;
var hei = screen.height-70;
var win7120=window.open(url,”ikkuna43″,’toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=’+wid+’,height=’+hei+'’);
moveTo(0,0);}

and this to prevent middle and right mouse click

34. EsaS - August 5, 2007

continue:

var message=”";
function clickIE() {if (document.all) {(message);return false;}}
function clickNS(e) {if
(document.layers||(document.getElementById&&!document.all)) {
if (e.which==2||e.which==3) {(message);return false;}}}
if (document.layers)
{document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
document.oncontextmenu=new Function(”return false”)

35. kapi - August 13, 2007

Hi Pig,

Thanks for this excellent script. Could you please tell me how I can do same for f4 etc keys.

Warm Regards,
Kapi

36. naveen - August 23, 2007

disable Ctrl+N option from (File -> New -> Window(Ctrl+N) in Internet Explorer) using javascript

37. kim - September 17, 2007

if i want to use this code for an entire page’s content that is enclosed within an iframe, how would one go about doing so?

thanks!

38. nishant - October 8, 2007

hi all!!

this code is not working in ie7, i checkd it in opera there its alright….but in ie7 it is not displaying message which i want to when ctrl is pressed

39. s.selvaraj - October 9, 2007

i want disabled my page when on button press in my screen .It is possible?

40. krishnamurthy.s - October 16, 2007

it is working nice

Thanks
Krishnamurthy.s
HCLTechnlogy

41. Raju - October 27, 2007

hi,
Gud work, and thanks for sharing your effort

Can any one tell me what changes i have to make to this script to disable Ctrl+X combination on the whole page?

42. Vijay - December 26, 2007

Thank U … I made some changes for me….

Itz working fine

Regards
Vijay

43. likon - January 15, 2008

Hey, did you think about what hapends when user turn off javascript? he can then copy everything.

44. Browser - Disable CTRL key - Ultrashock Forums - January 21, 2008

[…] google AS Workshop Disable ctrl + n and other ctrl + key combinations in JavaScript […]