Search code examples
javascriptformsevent-handlingdom-events

Disable context menu and copy-paste except on input fields


I have a client in an industry where a lot of content is often ripped directly from competitors' websites due to the quality of the content and its importance in SEO. To prevent this as much as possible the client wants to disable the right-click context menu as well as selecting, copying and pasting of text using JavaScript (we already have other non-JavaScript measures in place).

I've explained to them that the measures are unlikely to stop someone skilled with enough time and energy, but we both agree that they will be a major deterrent and help to significantly reduce the amount of content theft, especially since those most of those likely engaging in this behaviour are marketing and/or business people.

In addition, the nature of the site also means these measures are unlikely to affect UX much apart from on the input fields. How can I therefore implement this behaviour throughout the site while ensuring that it remains possible to edit any input fields as normal?


Solution

  • This is the only working solution for this I've been able to come up with so far. Any suggested improvements to it are more than welcome, and if anyone can come up with cleaner/more performant solutions (highly likely) then please do post them as an answer.

    function blockEvent(e) {
      e.preventDefault();
      e.stopPropagation();
      return false;
    }
    
    function enableEvent(e) {
      e.stopPropagation();
      return true;
    }
    
    document.addEventListener("contextmenu", blockEvent);
    document.addEventListener("cut", blockEvent);
    document.addEventListener("copy", blockEvent);
    document.addEventListener("selectstart", blockEvent);
    document.addEventListener("dragstart", blockEvent);
    
    let inputs = document.querySelectorAll("input");
    Array.prototype.slice.call(inputs).forEach((input) => {
      input.addEventListener("contextmenu", enableEvent);
      input.addEventListener("cut", enableEvent);
      input.addEventListener("copy", enableEvent);
      input.addEventListener("selectstart", enableEvent);
      input.addEventListener("dragstart", enableEvent);
    });