How to Disable Right Click Context Menu in Javascript
March 29, 2020
javascript
Disable browser right-click for the whole page
The browser fires the contextmenu
event when you right-click on a page. The context menu usually has a list of actions like "View Page Source" and "Back". We can prevent this menu from appearing on right-click by latching onto the contextmenu
event and using event.preventDefault()
. If we add this event listener to the window
object then we can prevent right-clicking on the whole page.
js
1.window.addEventListener("contextmenu", e => e.preventDefault());
Disable browser right-click for specific element
We can prevent right-clicking on any element by attaching the event listener to that specific element and calling event.preventDefault()
again.
js
1.const noRightClick = document.getElementId("myElement");2.3.noRightClick.addEventListener("contextmenu", e => e.preventDefault());
Disable context menu using oncontextmenu on an element
We can also disable the context menu by returning false on the oncontextmenu
attribute on the body
element.
html
1.<body oncontextmenu="return false;">2....3.</body>
Or on other elements:
html
1.<canvas oncontextmenu="return false;"></canvas>