This one could save you lot of time :-) In short, the answer is to “return false;”. That’s it. If you want to know more details, read ahead.

Say, you have an awesome page where you want to disable right click and also disable Ctrl+C (copy), Ctrl+S (save page). The process is simple. Just register an event for right click and when the event fires, just return false. Since false is being returned, the browser will cancel the event.

Same goes with keyboard. ‘onkeypress’ event is fired whenever a key is pressed. To reject any key, just capture that event and return false. If you want to do anything special, just do it before returning false. Ctrl+S is interesting. In most web browsers (notably google chrome), it brings up the default Save Dialog. Most web apps have keyboard shortcuts these days & oh! 99% of them don’t return false, only to find the user experience irritating when the save dialog pops up; when something else should occur. Hence, if you wish to customize the functionality of the default browser specific keyboard shortcuts, do the following:

  1. Create an event handler and capture the event.
  2. Do something.
  3. “return false;”

That’s all. Have fun!

2 Responses to “Cancelling default browser events in Javascript”

  1. whizz Says:

    am glad to read this.,, say i hv a flash in my site and i dont want ppl to copy/screenshot them., wat can u suggest other than watermarking which isnt wat i prefer..
    also., is there a way to prevent print screen button jus like wat u told ???
    vino

  2. Aswin Anand Says:

    @whizz: Yep all that is possible. But users typically have a workaround. They can do a wget or curl and get the necessary request on their desktop in no time.