How to disable printing on a website

Sometimes, we have some projects where the content is sensitive or should be protected for privacy reasons or copyrights. A quick solution involves:

  • To prevent the key combination Ctrl + P (for printing) via JS.
  • To prevent text selecting and copying text via JS.
  • To prevent right-clicking via JS.
  • To hide the whole page on printing via CSS.

<script>
    //Prevents Ctrl + P
//From https://stackoverflow.com/a/47848090/1928691
    window.addEventListener('keydown', function(event) {
        if (event.keyCode === 80 && (event.ctrlKey || event.metaKey)
&& !event.altKey && (!event.shiftKey || window.chrome || window.opera)) {
            event.preventDefault();
            if (event.stopImmediatePropagation) {
                event.stopImmediatePropagation();
            } else {
                event.stopPropagation();
            }
            return;
            }
    }, true);

    //Disables text selection and copying
//From https://gist.github.com/pbaruns/a24ad79b027956ed5d77fd3e6c201467
    if (typeof document.onselectstart != "undefined") {
        document.onselectstart = new Function("return false");
    }
    else {
        document.onmousedown = new Function("return false");
        document.onmouseup = new Function("return true");
    }

    //Prevents right click
document.addEventListener('contextmenu', event => event.preventDefault());
</script>

<style>
/*From https://stackoverflow.com/a/3359980/1928691*/
    @media print {
        html, body {
            display: none;  /* hide whole page */
        }
    }
</style>

Is it perfect? Of course, is not.

  • You might need to add a paywall to prevent its access.
  • You might need to add a DRM solution to prevent screenshots (that are often followed by OCRs to extract their text). Udemy does this already, you cannot take screenshots from several videos. You can take them if you use Firefox or less common browsers.
  • You will create accessibility issues.
  • The reader mode often bypasses common restrictions.
  • Some people can bypass it using the Dev Console and copy the text from the tags (Devs, RPAs, or geeks mainly?).
  • You might need to encrypt the text using a DRM service for anyone using the Dev Console.

This is just a quick solution that can support you in your journey.

Comments