Sign in
Log inSign up

Disable Right-Click Context Menu in JavaScript

Nathan's photo
Nathan
·Oct 6, 2021·

1 min read

When a user on your website or app right-clicks, the contextmenu event is triggered.

We can listen for this event by attaching an event listener to the window interface, but I'd suggest first adding the below one-liner to ensure compatibility with some older browsers:

typeof window.addEventListener === `undefined` && (window.addEventListener = (e, cb) => window.attachEvent(`on${e}`, cb));

Anyway, here is the actual snippet that will listen for the contextmenu event, intercept it, and prevent the default behavior:

window.addEventListener(`contextmenu`, (e) => {
    e.preventDefault();
});

Here is a one-liner variant that is equivalent to the above snippet:

window.addEventListener(`contextmenu`, (e) => e.preventDefault());

Conclusion

While exploring how you can create custom context menus is a bit beyond the scope of this article, I hope you found this snippet useful.

Remember to only disable context menus when absolutely necessary!

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct