Skip to content
Advertisement

Disable Right Click on WordPress Site

I wanted to disable right click on my wordpress site. I have written a small snippet and inserted into body which disables right click, CTRL events and keyups.

<body oncontextmenu="return false" onselectstart="return false" onkeydown="if ((arguments[0] || window.event).ctrlKey) return false"></body>

but it is annoying when I want to copy something on site. is there a way I can modify the current snippet like only logged in users would be able to access the disabled events?

Cheers.

Advertisement

Answer

First I have created a JS page in the directory named: “preventcopy.js” and added restricted the events using below JS

document.oncontextmenu = function() {
  return false
};
document.onselectstart = function() {
  if (event.srcElement.type != "text" && event.srcElement.type != "textarea" && event.srcElement.type != "password") return false;
    else return true;
  };
  if (window.sidebar) {
    document.onmousedown = function(e) {
      var obj = e.target;
      if (obj.tagName.toUpperCase() == "INPUT" || obj.tagName.toUpperCase() == "TEXTAREA" || obj.tagName.toUpperCase() == "PASSWORD") return true;
     else return false;
  }
};
if (parent.frames.length > 0) top.location.replace(document.location);

and then in function.php I enabled access for logged in users as below.

function copyrightpro_scripts() {
    wp_enqueue_script( 'copyrightpro', get_template_directory_uri() . '/copyprevent.js', array(), false );
}
if ( !is_user_logged_in() ) {
    add_action( 'wp_enqueue_scripts', 'copyrightpro_scripts' );
}

That’s how it is been accomplished. But I would highly suggest enabling these features for users considering the user experience.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement