Browser automation tools (Puppeteer, Playwright, CDP-based tools) fail silently
Browser automation tools (Puppeteer, Playwright, CDP-based tools) fail silently when injecting JavaScript into pages with strict Content Security Policy headers.
Symptoms:
page.evaluate() returns null or throws EvalErrorRuntime.evaluate via CDP returns {"result":{"type":"undefined"}}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.
Browser automation tools inject JavaScript in two ways:
eval() / Function(): Creates scripts from strings. Blocked by CSP unless 'unsafe-eval' is allowed.<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.
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.evaluateWhy 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.
# Launch Chrome with CSP disabled — NEVER use in production
chrome --disable-web-security --user-data-dir=/tmp/chrome-automationOr 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.
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"]})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);
""")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)
addScriptToEvaluateOnNewDocument is the most reliable bypass because it runs before CSP parsing. It works in headless Chrome, Chromium, and all Playwright/Puppeteer versions.Runtime.evaluate respects CSP. Page.addScriptToEvaluateOnNewDocument does not. This is by design — the latter is a browser-level injection, not a page-level eval.report-uri or report-to to log violations. Your automation may trigger violation reports even if the script executes successfully.browser-harness-cdp-browser-automation.md (CDP basics), feishu-block-api-false-success.md (API false success patterns).