There are some instances where you might want to disable right-click on a web page. For example, if you want to prevent easy downloading of video or images. Or when you want to replace the default browser right-click menu with a custom right-click menu.
This is easy to do using JavaScript:
window.addEventListener('contextmenu', function (e) {
// do something here...
e.preventDefault();
}, false);
Code language: JavaScript (javascript)
In this instance, the only thing the code is doing is preventing the right-click menu from appearing. It listens for the contextmenu
event, then the default functionality for this event (the appearing of the context menu) is disabled using the preventDefault()
method. Where the code includes a comment that says “do something here…” you could trigger a function that builds or inserts a custom right-click menu.
The demo below displays a message on the page each time the user tries to enable the right-click menu.