Disable Browser right click and F12 in a Blazor application


In most web applications you want to overwrite the default function of the browser right click.  This will allow you to add your own functionality for the right click in your application.  This will also disable the F12 functionality of the browser.

In this sample we will be showing how to disable the browser right click context menu and F12 but still show how to handle the right click in the Blazor application.
For the browser context menu disable we can use this code snippet.  This goes in the _host.cshtml file:

<body oncontextmenu="return false;">

To handle the F12 key disable we need to add this JavaScript to the bottom of the _host.cshtml file:

  window.onload = function () {
      document.addEventListener("contextmenu", function (e) {
          e.preventDefault();
      }, false);
      document.addEventListener("keydown", function (e) {
      //the I key
      if (e.ctrlKey && e.shiftKey && e.keyCode == 73) {
          disabledEvent(e);
      }
      //the J key
      if (e.ctrlKey && e.shiftKey && e.keyCode == 74) {
          disabledEvent(e);
      }
      //the S key + macOS
      if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
          disabledEvent(e);
      }
      //the U key
      if (e.ctrlKey && e.keyCode == 85) {
          disabledEvent(e);
      }
      //the F12 key
      if (event.keyCode == 123) {
          disabledEvent(e);
      }
      }, false);
          function disabledEvent(e) {
             if (e.stopPropagation) {
                 e.stopPropagation();
             } else if (window.event) {
                 window.event.cancelBubble = true;
             }
             e.preventDefault();
               return false;
         }
      };


How this works is that we can handle the right click in the Blazor application because it is closest to the source of the event.  If the Blazor application does not have a event handler then the event gets bubbled up to the next level until it reaches the browser at which point the above javascirpt handles the consumes the click event.


Code Sample

Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor - Cool Blur Loading Page

Blazor new and improved Search Box