Course contentsShow
← Web Development
Lesson 2842 of 2,98251. Content Security PolicyFree lesson

The script-src Directive

Controlling which JavaScript sources can execute using script-src to prevent malicious script injection.

The script-src Directive

What you'll learn: How to use the script-src directive to control which JavaScript sources can execute on your page and block malicious scripts.

Why script-src Matters

While default-src provides a broad safety net, JavaScript is where most security attacks happen. The script-src directive gives you fine-grained control over where scripts can load from, essentially creating a whitelist of trusted sources and blocking everything else—including inline scripts injected by attackers.

Think of it like a nightclub bouncer with a guest list: only scripts from approved sources get in.

How script-src Works

The script-src directive overrides default-src specifically for JavaScript. You define it in your CSP header or meta tag:

Content-Security-Policy: script-src 'self' https://cdn.example.com

This policy allows:

  • Scripts from your own origin ('self')
  • Scripts from https://cdn.example.com
  • Nothing else—not inline <script> tags, not eval(), not event handlers like onclick="..."

Common script-src Values

  • 'self' - Scripts from your domain only
  • 'unsafe-inline' - Allows inline <script> tags (dangerous, defeats XSS protection)
  • 'unsafe-eval' - Allows eval() and similar functions (avoid if possible)
  • 'nonce-' - Allows specific inline scripts with matching nonce attribute
  • Domain URLs - Specific trusted CDNs or third-party sources

Real-World Example

Content-Security-Policy: script-src 'self' https://cdn.jsdelivr.net https://www.google-analytics.com

This blocks an attacker's injected <script src="https://evil.com/steal.js"> while allowing your analytics and CDN resources.

Key Takeaway: The script-src directive is your primary defense against script injection attacks—whitelist only the JavaScript sources you trust and block everything else.