Content Copy Protection. Users Guide and Script "DevTools-Block".

This script is a multi-layered protection system designed to prevent copying and selection, as well as detect and neutralize attempts to open the developer toolbar.

Rating based on reviews:
Total stars received: 0
Total reviews: 0
Average rating: 0
Filed under: User Blog

Comprehensive Web Content Protection: Overview and Analysis of the Anti-Copying and DevTools Countermeasure Script

Introduction

Content — texts, images, and original creations — is constantly at risk of unauthorized copying for website owners. This can happen through standard browser tools (context menu, keyboard shortcuts) as well as through developer tools that allow extraction of the page’s source code.

The script presented below is a multi-layered protection system designed to prevent copying, text selection, and to detect and neutralize attempts to open the Developer Tools (DevTools). In this article, we will examine each component in detail, explain the logic behind it, evaluate its impact on performance and SEO, and provide practical recommendations for configuration and use.


1. Why Content Protection Is Needed

Without protection, malicious users or simply unscrupulous visitors can:

  • Copy an article’s text or product description with a single keystroke.
  • Save images while bypassing copyright.
  • Study the site’s structure in order to reproduce it later.
  • Bypass restrictions using built-in browser tools (for example, viewing the page source or the element inspector).

This problem is especially acute for websites with paid content, unique technical articles, photographs, and marketplaces where it is important to protect commercial information.


2. Overall Script Architecture

The script consists of four main logical blocks:

  1. Blocking DevTools shortcut keys – interception and cancellation of standard key combinations that open developer tools.
  2. Protection against selection, copying, and dragging – disabling the context menu, text selection, and image dragging.
  3. Blocking copy/cut/paste/print hotkeys – preventing the use of Ctrl+C, Ctrl+X, Ctrl+V, and Ctrl+P.
  4. Detection of open DevTools – monitoring window size changes to detect the developer panel even if it was opened via the browser menu.

When DevTools are detected, the page is completely cleared and a static message “Access Denied” is displayed, making it impossible to view the source code or work with the console.


3. Detailed Breakdown of Each Component

3.1. Blocking DevTools Shortcut Keys

document.addEventListener('keydown', function(e) {
 if (e.key === 'F12' ||
 (e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'J' || e.key === 'C')) ||
 (e.ctrlKey && e.key === 'U')) {
 e.preventDefault();
 return false;
 }
});

Purpose: intercepts keystrokes that traditionally open developer tools:

  • F12 – the standard way to open DevTools in all browsers.
  • Ctrl+Shift+I – opens the developer panel in Chrome/Edge/Firefox.
  • Ctrl+Shift+J – opens the console.
  • Ctrl+Shift+C – element selection (inspector).
  • Ctrl+U – view page source.

How it works: when such an event occurs, e.preventDefault() is called, which cancels the browser’s default action. The additional return false ensures the event does not bubble up to other handlers.

Important: this is the first line of defense, but it can be bypassed by opening DevTools through the browser’s main menu. That is why the next block — detection by window size — is essential for reliability.

3.2. Blocking the Context Menu, Selection, and Dragging

document.addEventListener('contextmenu', e => e.preventDefault());
document.addEventListener('selectstart', e => e.preventDefault());
document.addEventListener('dragstart', e => e.preventDefault());
  • contextmenu – disables the context menu triggered by the right mouse button.
  • selectstart – prevents text and other elements from being selected with the mouse.
  • dragstart – disables dragging of images and links.

These three handlers close off most of the simple ways to copy or save elements from the page.

3.3. Blocking Copy, Cut, Paste, and Print Hotkeys

document.onkeydown = function(e) {
 if (e.ctrlKey && (e.key === 'c' || e.key === 'x' || e.key === 'v' || e.key === 'p')) {
 e.preventDefault();
 }
};

The onkeydown handler intercepts the combinations Ctrl+C, Ctrl+X, Ctrl+V, and Ctrl+P.
e.ctrlKey also accounts for the Cmd key on macOS.
Cancelling the action prevents copying, cutting, pasting, and printing the page.

3.4. Detecting Open DevTools by Analyzing Window Size

let devtoolsOpen = false;
function detectDevTools() {
 const threshold = 160;
 const widthDiff = window.outerWidth - window.innerWidth;
 const heightDiff = window.outerHeight - window.innerHeight;
 if (widthDiff > threshold || heightDiff > threshold) {
 if (!devtoolsOpen) {
 devtoolsOpen = true;
 reactToDevTools();
 }
 } else {
 devtoolsOpen = false;
 }
}

Operating principle:
When the developer panel is open, the browser reduces the internal viewport area (window.innerWidth/innerHeight), while the outer window dimensions (window.outerWidth/outerHeight) remain unchanged. The difference between these values becomes significant (usually more than 160 pixels). This threshold was chosen empirically: most DevTools panels occupy at least 160 pixels in width or height.

Why threshold = 160:
If DevTools are docked at the bottom, the inner window height decreases by the height of the panel. If docked on the side, the width decreases. In rare cases with a very small screen, a false positive is possible, but the probability is low.

Handling changes:

  • The check runs every 25 seconds via setInterval. This keeps the load minimal while ensuring timely detection.
  • Additionally, the check is triggered on the resize event, allowing an instant reaction when DevTools are opened as a panel that changes the window size.

3.5. Reaction to Detected DevTools

function reactToDevTools() {
 document.documentElement.innerHTML = '';
 document.body.innerHTML = '<div style="text-align:center; margin-top:20%; font-family:sans-serif;">Access Denied</div>';
}

When DevTools are detected, the entire page is cleared: all content of <html> is removed, and a new body is created with the message. This guarantees that even if the user tries to inspect the DOM via the console, they will see only an empty structure.

Alternative actions:
The code comments show an option to redirect to google.com. However, as will be discussed later, redirecting to an external site can have negative consequences for SEO and UX. It is recommended to use page clearing with a message or, if necessary, redirect to a special page on your own site.


4. Why This Approach Is Safe for Search Engines

Search engine crawlers (Googlebot, Yandex.Bot, and others) do not open developer tools and do not have a graphical window. Therefore, resize events do not occur for them, and the difference between window.outerWidth and window.innerWidth is always zero. Consequently, the detectDevTools() function will never return true for a bot.

Search engines see the full version of the page, index it normally, and no penalties for “cloaking” will be applied.

Important: if we used a redirect to another domain, it could raise suspicions of serving different content to bots and users. Clearing the page when DevTools are open is not cloaking, because a crawler will never find itself in that situation.


5. Impact on Performance

  • setInterval with a 25-second interval – a very infrequent check that places virtually no load on the processor. Even if the frequency is increased to 1–2 seconds, modern computers will not notice the difference, but 25 seconds is a safe minimum.
  • The resize event – fires only when the window size changes, which happens rarely. It creates no additional load.
  • Keyboard and mouse handlers – fire only during active user actions. Their impact on performance is negligible.

The script does not use heavy operations such as continuous DOM checks or animations, so its implementation is practically invisible to the site’s performance.


6. Potential Drawbacks and Limitations

  1. False positives with a very small browser window
    If a user deliberately shrinks the browser window to a very small size, the difference between the inner and outer areas may exceed the 160-pixel threshold. This will trigger the protection and clear the page. Solution: either increase the threshold (for example, to 200) or use more advanced detection methods (such as checking for the window.devtools property or emulation). However, those methods are less reliable.
  2. Bypass in browsers that do not support outerWidth/outerHeight
    Some older or mobile browsers may not support these properties. However, they work reliably in modern desktop browsers. On mobile devices, DevTools are usually opened via remote debugging, so protection against them is not required.
  3. Page clearing after DevTools are opened may cause inconvenience
    Legitimate users (for example, developers testing their own site) may accidentally open DevTools and lose the content. It is recommended to add the ability to temporarily disable protection for administrators (for example, by checking for a cookie or a specific URL parameter).
  4. It is impossible to block all copying methods completely
    No script can provide 100% protection. A user can always disable JavaScript, take a screenshot, use browser extensions that bypass protection, or employ third-party programs to extract content. Nevertheless, the presented protection significantly complicates unauthorized copying and deters most casual violators.

7. Configuration and Usage Recommendations

  1. Place the script at the end of the <body> tag – this ensures it loads after the main content has rendered and does not slow down page display.
  2. Configure the check interval – if you need a faster reaction, reduce the interval to 1–2 seconds. At the same time, make sure site performance is not affected.
  3. Choose a suitable threshold (threshold) – if your layouts have a fixed width, 160 can be left as is. For responsive sites that allow strong window shrinking, increase the threshold to 200–250.
  4. Avoid redirecting to external sites – it is better to clear the page or redirect to your own page with an explanation if necessary.
  5. Add an exception for authorized users – for example, if the site has a login system, you can check for a session and skip protection for administrators.
  6. Test in different browsers – make sure the script works correctly in Chrome, Firefox, Edge, and Safari.

8. Alternative Content Protection Methods

In addition to JavaScript protection, there are other approaches:

  • Server-side content generation – outputting text as images or PDF.
  • Watermarks – on images and even on text (using CSS pseudo-elements).
  • Prevent indexing of fragments – using robots.txt or meta tags, but this does not protect against users.
  • Using CAPTCHA for content access – raises the entry barrier.

Combining several methods delivers the best results.


Conclusion

The presented script is an effective solution for protecting web content from copying and unauthorized viewing of source code. It combines several layers of protection:

  • Blocking standard keyboard combinations and the context menu.
  • Preventing text selection and image dragging.
  • Intelligent detection of developer tools through window-size analysis.
  • Instant reaction with page clearing upon threat detection.

The script has no significant impact on performance, is safe for SEO, and is simple to configure. However, you should take into account possible false positives with non-standard window sizes and plan a mechanism to disable protection for legitimate administrators.

By using this code, you create an additional barrier that makes unauthorized copying of your content significantly more difficult — and for most visitors, simply impossible. In the highly competitive online environment, such protection becomes an important element in preserving the uniqueness and value of your website.



Reviews

No reviews yet


Comments (0)

No comments yet
Only registered users can post new comments

Recommended Products and Services

Cotonti CMF: Plugin Installation, Integration, and Adaptation

Cotonti CMF: Plugin Installation, Integration, and Adaptation

professional services for the installation, deep integration and adaptation of plug-ins for Cotonti

Content author

webitproff

Offline

Sodium Carbonate

Last logged: 2026-07-19 01:57

  • Чем могу помочь?

    Оказываю весь спектр услуг по CMF Cotonti. Разработка открытых и закрытых корпоративных интернет порталов, небольших социальных сетей, торговые площадки, маркетплейсы, биржи фриланса, каталоги товаров оптовых поставщиков, интернет-магазин под заказ, чтобы делать совместные покупки и групповые совместные продажи от имени нескольких продавцов.

  • Разработки на GitHub бесплатно
    • Page published: 2026-03-25 14:27
    • Last update: 2026-03-25 14:57
    • Language:

    Связанные статьи