Event Handlers and Inline Attributes
What You'll Learn
You'll understand why inline event handlers like onclick can't use nonces and require the looser 'unsafe-inline' directive in your CSP.
The Problem with Inline Event Handlers
By now, you've learned that CSP nonces and hashes are powerful tools for allowing specific inline scripts and styles while blocking everything else. But there's a critical limitation: nonces and hashes don't work with inline event handlers.
Inline event handlers are attributes like onclick, onload, onerror, or onmouseover directly in your HTML:
<button onclick="doSomething()">Click me</button>
<img src="photo.jpg" onerror="handleError()">
Even if you add a nonce to these elements, the browser ignores it:
<!-- This WILL NOT WORK -->
<button nonce="abc123" onclick="doSomething()">Click me</button>
Why This Happens
CSP nonces and hashes apply to <script> and <style> blocks, not to JavaScript embedded in element attributes. The browser treats inline event handlers as a separate, inherently risky category. To allow them, you must use 'unsafe-inline' in your script-src directive—which unfortunately permits all inline scripts, not just your event handlers.
The Better Alternative
Instead of inline handlers, attach event listeners in external or nonce-protected scripts:
// In a script with proper nonce
document.querySelector('button').addEventListener('click', doSomething);
This keeps your CSP strict and your code more maintainable.
Key Takeaway: Inline event handlers like onclick don't support nonces or hashes and require 'unsafe-inline', which weakens your CSP. Always prefer external event listeners attached via JavaScript instead.