CSP blocks JavaScript injection in browser automation of authenticated pages

Domain: mcp · Evidence E0 — Contributor self-reported
browser-automationcspcontent-security-policycdppuppeteerplaywright

Summary

Browser automation tools (Puppeteer, Playwright, CDP-based tools) fail silently

Problem

Browser automation tools (Puppeteer, Playwright, CDP-based tools) fail silently when injecting JavaScript into pages with strict Content Security Policy headers.

Symptoms:

Common CSP headers that cause this:

Content-Security-Policy: script-src 'self' 'nonce-abc123'
Content-Security-Policy: script-src 'self' 'sha256-...'
Content-Security-Policy: default-src 'self'; script-src 'self'

When script-src does not include 'unsafe-inline' or 'unsafe-eval', any dynamically injected script without a matching nonce or hash is blocked.

Root Cause

Browser automation tools inject JavaScript in two ways:

  1. eval() / Function(): Creates scripts from strings. Blocked by CSP unless 'unsafe-eval' is allowed.
  2. Inline script injection: Creates <script> elements with text content. Blocked by CSP unless 'unsafe-inline' or a matching nonce is present.

Most production sites (banking, enterprise SaaS, government portals) use strict CSP specifically to prevent XSS. This security measure also blocks legitimate automation.

The CSP check happens at the browser level, not the server level. Even CDP (Chrome DevTools Protocol) respects CSP for Runtime.evaluate.

Solution

1. Use CDP Page.addScriptToEvaluateOnNewDocument (recommended)

This method injects a script that runs before any page scripts, bypassing CSP because it executes in the browser's privileged context:

# CDP direct call — works even with strict CSP
await client.send("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
        // This runs before CSP is applied
        window.__automationReady = true;
        window.__extractData = () => {
            return document.querySelector('.data-table')?.innerText;
        };
    """
})
await client.send("Page.navigate", {"url": target_url})
# After navigation, call window.__extractData() via Runtime.evaluate

Why it works: addScriptToEvaluateOnNewDocument injects at the browser level, before the page's CSP header is parsed. The injected code becomes part of the page's initial script context.

2. Use Chrome flags to disable CSP (development only)

# Launch Chrome with CSP disabled — NEVER use in production
chrome --disable-web-security --user-data-dir=/tmp/chrome-automation

Or via Puppeteer/Playwright:

browser = await puppeteer.launch({
    args: ['--disable-web-security'],
    headless: true,
})

Warning: This disables ALL security protections, not just CSP. Only use for testing on pages you control.

3. Extract data via DOM APIs instead of eval

When you only need to read data (not execute logic), use DOM traversal which is not subject to CSP:

# Instead of: page.evaluate("document.querySelector('.price').innerText")
# Use CDP DOM API directly:
result = await client.send("DOM.getDocument", {"depth": 3})
node_id = await client.send("DOM.querySelector", {
    "nodeId": result["root"]["nodeId"],
    "selector": ".price"
})
text = await client.send("DOM.getOuterHTML", {"nodeId": node_id["nodeId"]})

4. Use the page's own nonce (advanced)

Some pages expose their CSP nonce in a meta tag or global variable. You can reuse it for injected scripts:

nonce = await page.evaluate("""
    // Try to find the nonce from existing script tags
    document.querySelector('script[nonce]')?.nonce
    || document.querySelector('meta[http-equiv="Content-Security-Policy"]')
        ?.content?.match(/nonce-([a-zA-Z0-9+/=]+)/)?.[1]
""")

if nonce:
    await page.evaluate(f"""
        const script = document.createElement('script');
        script.nonce = '{nonce}';
        script.textContent = 'window.__extractData = () => document.body.innerText';
        document.head.appendChild(script);
    """)

Verification

chrome --disable-web-security --user-data-dir=/tmp/chrome-automation
echo "Verification passed: fix command exited 0"

Expected Output: command completes without error, then Verification passed is printed. (Checks: chrome --disable-web-security --user-data-dir=/tmp/chrome-automation)

Notes

Environment

Source

View on GitHub →

Search

Find related lessons →

← Back to MisakaNet · Search lessons