User Tools

Site Tools


web_sites:disable_right-clicking_by_using_javascript

Web Sites - Disable right-clicking by using JavaScript

Simply add the following JavaScript code to the <body> section of your web page:

<script language="JavaScript">
/**
  * Disable right-click of mouse, F12 key, and save key combinations on page
*/
 
window.onload = function() 
{
  document.addEventListener("contextmenu", function(e){
    e.preventDefault();
  }, false);
  document.addEventListener("keydown", function(e) {
  //document.onkeydown = function(e) {
    // CTRL + A
    if (e.ctrlKey && e.keyCode == 65) {
      disabledEvent(e);
    }
    // CTRL + C
    if (e.ctrlKey && e.keyCode == 67) {
      disabledEvent(e);
    }  
    // "C" key
    if (e.ctrlKey && e.shiftKey && e.keyCode == 67) {
      disabledEvent(e);
    }
    // "I" key
    if (e.ctrlKey && e.shiftKey && e.keyCode == 73) {
      disabledEvent(e);
    }
    // "J" key
    if (e.ctrlKey && e.shiftKey && e.keyCode == 74) {
      disabledEvent(e);
    }
    // "S" key + macOS
    if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
      disabledEvent(e);
    }
    // "U" key
    if (e.ctrlKey && e.keyCode == 85) {
      disabledEvent(e);
    }
    // "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;
  }
};
</script>

This code will block the right click of mouse, Ctrl+A, Ctrl+C, Ctrl+Shift+C, Ctrl+Shift+I, Ctrl+Shift+J, Ctrl+S, Ctrl+U, and F12 key.

The F12 key uses for looking the source code of page, so it also need be disabled.

Also, for addition, you can add the oncontextmenu attribute to the <body> tag of your page HTML code:

<body oncontextmenu="return false;">
web_sites/disable_right-clicking_by_using_javascript.txt · Last modified: 2020/07/15 09:30 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki