Disable Right-Click (Context Menu) with JavaScript

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);

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.

Note: To the best of our knowledge, the information above and the snippet are accurate and up to date. However, in case you notice something wrong, please report snippet or leave a comment below.
Back to Snippets
Disqus Comments Loading...

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!