Chapter 66: Content Security Policy (CSP)

Real-Time CSP Violation Handling & DOM Listeners

**Part 14: Security & Best Practices** — Chapter 66: Content Security Policy (CSP)

LEARNING OBJECTIVES
  • Listen for in-browser CSP violations via the securitypolicyviolation DOM event.
  • Inspect violation properties: blockedURI, violatedDirective, effectiveDirective, originalPolicy.
  • Filter out noisy browser extension false-positives (Grammarly, LastPass).
  • Transmit client-side security alerts to monitoring backends in real time.
🎬 INTERACTIVE VISUAL PIPELINE Core Architecture Simulation
🌐
1. Input
Directives & Tags
⚙️
2. Parse
Tokenizer & AST
🌳
3. Layout
Box Model & Flow
🎨
4. Render
GPU Paint & Composite
PHASE 1: INPUT & DIRECTIVES
Browser receives declarative markup stream, parsing tag tokens and initializing component state.

💻 Interactive Code Playground


document.addEventListener('securitypolicyviolation', (e) => {
  // Ignore known benign browser extension injection noise
  if (e.blockedURI.startsWith('chrome-extension://') || e.blockedURI.startsWith('moz-extension://')) {
    return;
  }

  const payload = {
    blockedURI: e.blockedURI,
    violatedDirective: e.violatedDirective,
    originalPolicy: e.originalPolicy,
    disposition: e.disposition, // 'enforce' or 'report'
    statusCode: e.statusCode,
    sourceFile: e.sourceFile,
    lineNumber: e.lineNumber,
    columnNumber: e.columnNumber,
    timestamp: new Date().toISOString()
  };

  console.error('🚨 CSP VIOLATION DETECTED:', payload);
  
  if (navigator.sendBeacon) {
    navigator.sendBeacon('/api/security/csp-telemetry', JSON.stringify(payload));
  }
});

📌 Key Takeaways

  • The securitypolicyviolation event fires directly in the browser DOM whenever any resource violates CSP.
  • Use e.disposition to determine whether the violation was in Report-Only or Enforced mode.
  • --

❓ Knowledge Check

1. Which of the following is correct?

2. Which of the following is correct?