How to disable the browser rightclick menu#

One may want to disable the right click context menu on a webpage for various reason. It could be to show a custom context menu or to prevent images from being downloaded, etc.

Disabling the context menu does not prevent your images from beind downloaded. They can easily be accessed from the "Sources" tab in the Developer Tools. Or one can take a screenshot, if they are too lazy to open Developer Tools.

The context menu can easily be disabled using the DOM API. There are two ways of going about it.

The first way is the inelegant way. You add this piece of inline JavaScript code to the HTML body tag of your webpage.

<body oncontextmenu="return false">

The second way, the elegant way, is to nclude this snippet of JavaScript in your webpage.

document.oncontextmenu = function() {
  return false;
}

There you go! You now have disabled context menu, no more rightclicking.

Demo#

<button onclick="document.oncontextmenu = function() { return false; }">Click to disable context menu</button>
<button onclick="document.oncontextmenu = function() { return true; }">Click to enable context menu</button>

Notes#

  1. This is the technique of disabling the rightclick on a webpage
  2. The technique will fail if the user disables JavaScript
  3. The second way of disabling the contextmenu (the elegant way) is the recommended way to do it

Exercise#

  1. How do you create a custom context menu for a webpage?
  2. Why is the second way, the recommended way?

References#

  1. WikiPedia - DOM Events
  2. MDN - oncontextmenu Event