User Agents

Web browsers and everyday web tech, explained

Detect Browser Screenshot Events with JavaScript

· 6 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Detecting when a user takes a screenshot of your web page is not directly possible with JavaScript, but you can approximate it using visibility changes, blur events, and the Page Visibility API. This guide shows you how to build a reliable heuristic that triggers when a screenshot is likely taken, useful for analytics, watermarking, or UI adjustments.

What You'll Need

  • A modern browser (Chrome, Firefox, Edge, Safari) for testing.
  • Basic knowledge of JavaScript and event listeners.
  • A code editor and a local or hosted HTML file.

Step-by-Step

  1. Create a basic HTML page with a content area you want to monitor. For example, add a <div id="content"> with some text or an image.
  2. Add a script tag before the closing </body> tag. This is where all your detection code will live.
  3. Set up a flag to track visibility state. Use document.visibilityState to know if the tab is currently visible. Initialize a variable like let isPageVisible = !document.hidden;.
  4. Listen to the visibilitychange event. This fires when the tab becomes hidden or visible. When the page becomes hidden, it could be because the user switched tabs, minimized the browser, or took a screenshot (on some systems, screenshot tools cause the page to lose focus).
  5. Listen to the blur event on the window. This fires when the window loses focus. Screenshot tools (like the built-in Windows Snipping Tool or macOS Cmd+Shift+4) often trigger a blur event because the page loses focus.
  6. Combine both events with a timing heuristic. When the page becomes hidden or blurred, start a timer (e.g., 500ms). If the page becomes visible again within that short window, it's likely a screenshot was taken. If it stays hidden longer, it's probably a tab switch or minimization.
  7. Implement the detection logic. Here's a complete example:
    let wasHidden = false;
    let blurTimer = null;
    
    function onScreenshotDetected() {
      console.log('Screenshot likely taken!');
      // Add your custom logic here (e.g., send analytics, show a watermark)
    }
    
    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        wasHidden = true;
        // Start a timer to see if we come back quickly
        setTimeout(() => {
          if (document.hidden) {
            wasHidden = false; // It was a real hide, not a screenshot
          }
        }, 500);
      } else {
        if (wasHidden) {
          onScreenshotDetected();
          wasHidden = false;
        }
      }
    });
    
    window.addEventListener('blur', () => {
      // Start a short timer; if we get focus back quickly, it's likely a screenshot
      blurTimer = setTimeout(() => {
        blurTimer = null;
      }, 500);
    });
    
    window.addEventListener('focus', () => {
      if (blurTimer) {
        clearTimeout(blurTimer);
        blurTimer = null;
        onScreenshotDetected();
      }
    });
  8. Test your implementation. Open the page in your browser, press the screenshot shortcut (e.g., Cmd+Shift+4 on macOS, or Win+Shift+S on Windows) and check the console for the log. Note that the detection may not fire if the screenshot tool doesn't blur the page (some tools work in a way that doesn't trigger blur).
  9. Refine the timing. Adjust the 500ms threshold based on your testing. Some screenshot tools may take longer to complete, so you might need to increase it to 1000ms. However, a longer threshold increases false positives (e.g., quick tab switches).
  10. Add a fallback for mobile. On mobile devices, screenshots are often taken via hardware buttons (e.g., power + volume down). These don't trigger blur or visibility changes reliably. You can listen to the resize event as a rough heuristic, but it's unreliable. For mobile, consider using a library like html2canvas to detect canvas-based screenshots, but that's a different approach.

Common Mistakes

  • Assuming 100% accuracy: No method can guarantee detection. Screenshot tools vary across operating systems and browsers. Your heuristic will miss some screenshots and may falsely trigger on other actions.
  • Using only blur event: Many screenshot tools don't blur the window, especially on macOS where the screenshot overlay appears without losing focus. Always combine with visibility changes.
  • Not clearing timers properly: If you don't clear the timer when the page becomes visible again, you might get false positives. Always clear the timeout in the focus handler.
  • Ignoring browser differences: Safari and Firefox may behave differently. Test in multiple browsers to fine-tune your thresholds.

Tips

  • Use a longer threshold for desktop: Desktop screenshot tools often take 1-2 seconds to complete. A 1000ms threshold works better than 500ms on desktop, but test it.
  • Combine with mouse events: If the user clicks a button before taking a screenshot, you can use that as a signal. For example, if they click a "screenshot" button in your UI, you can trigger the detection logic.
  • Log the event for analytics: Send an analytics event when detection fires to understand how often users screenshot your content. This can inform your content strategy.
  • Consider using a library: Some libraries like screenshot-detector (if it exists) might simplify the process, but be cautious about dependencies and security.

Troubleshooting

  • Detection never fires: Check if your browser's screenshot tool actually blurs the page. Test with a simple alert on blur to confirm. If not, you may need to rely solely on visibility changes, which also may not fire. In that case, detection is not possible for that tool.
  • False positives on tab switch: If you switch tabs quickly and the detection fires, increase the threshold (e.g., to 1000ms). But be aware that very fast tab switches might still trigger false positives.
  • Detection fires too late: If the screenshot is taken and you need to react instantly, the timing heuristic may not be fast enough. Consider using a mousemove or keydown listener to detect the screenshot shortcut key combination, but that's not reliable across all systems.
  • Mobile screenshots not detected: As mentioned, mobile is unreliable. If you need to detect mobile screenshots, you might need to use a different approach like detecting the visibilitychange when the screen orientation changes, but it's still not robust.

Frequently Asked Questions

Can I detect a screenshot with 100% accuracy?

No. JavaScript cannot directly access the browser's screenshot functionality. The heuristic method described here is the best you can do, and it will have false positives and negatives.

Does this work on all browsers?

It works on modern browsers that support the Page Visibility API and the blur/focus events. However, the behavior of screenshot tools varies by OS and browser, so you may need to adjust thresholds.

Can I prevent users from taking screenshots?

No. You cannot prevent screenshots. You can only detect them after the fact. Attempting to block screenshots is not possible with web technologies.

Will this affect performance?

Minimally. The event listeners and timers are lightweight. However, if you have many listeners or complex logic in the detection callback, it could impact performance. Keep the callback simple.

Can I use this to protect copyrighted content?

It can help you track when screenshots are taken, but it cannot stop them. You might use it to show a watermark or send a legal notice, but it's not a robust protection mechanism.

Is there a way to detect screenshots on mobile?

Mobile detection is unreliable. Some Android devices fire a visibilitychange when the screenshot is taken, but iOS generally does not. You could try listening to the resize event, but it's not dependable.