How to Disable right click on a webpage using JavaScript

In this tutorial, we will learn how to disable right-click on a webpage using JavaScript.

Disable right click on a webpage using JavaScript

Here I am going to describe one efficient method.

We can disable the right click on a webpage using the preventDefault event to disable contextmenu event by using Javascript.

1. Javascript code

document.addEventListener('DOMContentLoaded', (event) => {
    document.addEventListener('contextmenu', (e) => {
        e.preventDefault();
    });
});

Explanation:

The above Javascript code that is provided is for block the right click event on the web page, and this is done using the contextmenu event and preventing its default action.

2. Javascript inscribed in HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Disable Right Click</title>
    <script>
        document.addEventListener('DOMContentLoaded', (event) => {
            document.addEventListener('contextmenu', (e) => {
                e.preventDefault();
            });
        });
    </script>
</head>
<body>
    <h1>Right Click Disabled</h1>
    <p>Try to right-click on this page. It won't work!</p>
</body>
</html>

Explanation:

The JavaScript code added in the HTML code disables the right-click functionality on the webpage. The code works by adding an event listener for the contextmenu event to the document. Once the DOM (Document Object Model) is fully loaded into the webpage, the event listener is set up. So, when someone tries to right-click on the page, the contextmenu event fires. The event listener then stops this event by calling the preventDefault() method on the event object e. As a result, the right click event is disable.

Leave a Reply

Your email address will not be published. Required fields are marked *