skip to Main Content

How to disable or remove only Inspect element function from right click menu with help of Javascript or jQuery

I know you can completely disable right click with e.preventDefault());

document.addEventListener('contextmenu', e => e.preventDefault());

And i want Right Click menu works with all options except inspect element, it disable only inspect element function in right click menu.

like it find the word *inspect* in menu option and disable that option which contain word *inspect*

is that any solution for this in Javascript or jQuery

2

Answers


  1. you can loop all menu items and block them

    document.addEventListener('contextmenu', function(e) {
      e.preventDefault();
    
      for (let i = 0; i < e.target.children.length; i++) {
        const menuItem = e.target.children[i];
    
        // Check "Inspect"
        if (menuItem.textContent.toLowerCase().includes('inspect')) {
          // Prevent the default action for this specific item
          menuItem.addEventListener('click', function(e) {
            e.preventDefault();
          });
        }
      }
    });
    
    Login or Signup to reply.
  2. You have limited options and none of them will really solve the problem you propose. The issue is that the inspect option is part of the browser, which is running on the users computer, that you don’t have access to. As has been stated on other SO threads before, there are numerous ways for the user to still inspect the element using the keyboard, browser main menus or even just by looking at the raw HTTP response via curl request or in tools like postman.

    What you can do is prevent the user from interacting but only in a finite, narrow focused way.

    This is a really simple solution that is not user friendly but if you just give the elements you don’t want inspected a class or data- attribute then you can check for this condition and prevent the inspect. However, this will disable any right-click option on that element and as you may have guessed the user will still be able to do this on another element and traverse from there:

    document.addEventListener('contextmenu', function(e) {
        if (e.target.dataset.inspect === "false"){ //< Option 1
        //if (e.target.classList.contains('no-inspect')){ // //< Option 2
            e.preventDefault();
        }
    });
    <section data-inspect="false" class="no-inspect" style="padding: 5rem; margin:2rem; background: blue; text-align:center; color:white">Can't Inspect</section>
    <section style="padding: 5rem; margin:2rem; background:red; text-align:center; color:white">Inspect</section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search