Block any Event of Browser using Javascript codes

In most browsers there are three possible kinds of events triggered when a keyboard key is pressed or released,

  1. keydown
  2. keypress
  3. keyup

You can check which key was pressed or released whenever KeyboardEvent is triggered because that event contains information and based on that event information you can write you custom logic to handle that event.

Note

The implementation will fail if the user disables JavaScript.

Base Code to trace any javascript event,

document.addEventListener("keydown", function(event)  
{  
   console.log(event.which);  
   console.log(event.keyCode);  
   console.log(event.shiftKey);  
   console.log(event.altKey);  
   console.log(event.ctrlKey);  
   console.log(event.metaKey);  
}   

List of Avaibale Javascript Code

This is image title

We can use the below code to prevent opening of context menu, copy cut paste, or view source code on any page.

Many times we want to disable some existing functionality on a webpage for any security reason.

Eg: prevent images from being downloaded, copy the content, etc…,

Disable context menu on right click,

$("body").on("contextmenu", function (e)
   {
      return false;
   });
});

Or,

document.oncontextmenu = function() {
   return false;
}

Disable right click menu on particular section on page,

$(document).ready(function(){
   $("#youDivSectionId").bind("contextmenu", function(e) {
      return false;
   });
});

Disable Cut, copy, paste,

$(document).ready(function(){
   $('body').bind('cut copy paste', function (e)
   {
      e.preventDefault();
   });
});

Let’s Block the same cut, copy, paste events with javascript codes,

$(document).ready(function(){
$(document).keydown(function(event) {
   //event.ctrlKey = check ctrl key is press or not
   //event.which = check for F7
   // event.which =check for v key
   if (event.ctrlKey==true && (event.which == '118' || event.which == '86')) {
      event.preventDefault();
      }
   });
});

Prevent browser Debugger console example,

$(document).keydown(function (event) {
// Prevent F12 -
if (event.keyCode == 123) {
   return false;
}
// Prevent Ctrl+a = disable select all
// Prevent Ctrl+u = disable view page source
// Prevent Ctrl+s = disable save
if (event.ctrlKey && (event.keyCode === 85 || event.keyCode === 83 || event.keyCode ===65 )) {
   return false;
}
// Prevent Ctrl+Shift+I = disabled debugger console using keys open
else if (event.ctrlKey && event.shiftKey && event.keyCode === 73)
{
   return false;
}
});

Thank you for reading ! I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

#javascript #code #programming #developer

Block any Event of Browser using Javascript codes
15.40 GEEK