Monday, January 19, 2004

How To Disable Browser HotKeys Using JavaScript

I noticed that a number of people were getting to my blog searching at Google for how to disable web browser hotkeys, so I figured I'd make them happy by writing a blog showing how to do this.

NOTICE: I saw in my logs that some people searching for disabling CTRL-P were sent to this page by Google. If you're interested in disabling printing from a web page using JavaScript, see this blog entry instead.

First of all, let me say that disabling hotkeys in a browser is by no means a certain prospect using javascript. I have never had success disabling the alt-keys for built-in browser menu items, and the way the browser handles the hotkeys tends to vary from browser to browser. So...

NOTICE: Do not rely on JavaScript attempts to disable hotkeys as an iron-clad security measure! There's no guarantees!

However, that said, here's a method that works in IE 4 and above. I have the code setup for Netscape as well, just in case you want to use the code to trap keys in Netscape and IE (but they will only be successfully disabled in IE).

function keyTrap(e)

// Netscape uses e, IE window.event
var eventObj = (e)?e:window.event;
var keyPressed = (e)?e.which:window.event.keyCode;
var ctrlPressed = (e)?(e.ctrlKey):window.event.ctrlKey;

if (ctrlPressed)
switch (keyPressed)
case 80: // CTRL-P.
window.event.keyCode = 0;
return false;


This code disables only CTRL-P, which can be useful in preventing printing of a page. It doesn't work at all if the user has Netscape. The key is trapped, but the Print dialog still comes up. Even if you try to set e.which to 0, it still does not work.

SOAPBOX: Herein lies one of the most frustrating aspects of building web applications. You have to have six copies of various versions of browsers available if you want 100% compatability. ASP.NET promised it would take care of this problem, and it does a very good job at doing so for its built-in components. However, despite ASP.NET's greatly expanded capabilities over ASP, I have yet to create a web project that does not need at least some javascript coding. And Microsoft and Netscape bicker and fuss over who's version of javascript is correct. Microsoft is notorious for adding in their own functionality without anybody else's approval, and Netscape is notorious for not duplicating it in the same way (even if they think it's a great idea--it's like they give a property its own name in javascript that is different from the one Microsoft gave it--even if it does exactly the same thing!--just so it will be different from Microsoft).

Okay, off the soapbox.

That's it for today. Feel free to email me with any questions or comments.