Inline Script Violations
Inline Script Violations
The most common CSP error involves inline scripts being blocked when transitioning from permissive to restrictive policies. This error manifests as functionality breaking without clear indication of the cause, particularly affecting legacy applications and third-party integrations.
Understanding and fixing inline script violations:
// Common Error: Inline script blocked
// Console: Refused to execute inline script because it violates the following
// Content Security Policy directive: "script-src 'self'"
// PROBLEM: Inline event handlers
<button onclick="handleClick()">Click me</button>
<div onmouseover="showTooltip(this)">Hover for info</div>
// SOLUTION 1: Move to external scripts with event listeners
// HTML:
<button id="action-button">Click me</button>
<div class="tooltip-trigger" data-tooltip="info">Hover for info</div>
// JavaScript:
document.addEventListener('DOMContentLoaded', function() {
// Replace onclick
document.getElementById('action-button').addEventListener('click', handleClick);
// Replace onmouseover
document.querySelectorAll('.tooltip-trigger').forEach(element => {
element.addEventListener('mouseover', function() {
showTooltip(this);
});
});
});
// SOLUTION 2: Use nonces for necessary inline scripts
// Server-side (Express.js):
app.use((req, res, next) => {
const nonce = crypto.randomBytes(16).toString('base64');
res.locals.nonce = nonce;
res.setHeader(
'Content-Security-Policy',
`script-src 'self' 'nonce-${nonce}';`
);
next();
});
// HTML template:
<script nonce="<%= nonce %>">
// This inline script is now allowed
function criticalInlineFunction() {
console.log('Inline script with nonce');
}
</script>
// SOLUTION 3: Use hashes for static inline scripts
// Calculate hash of script content
const scriptContent = `console.log('Static inline script');`;
const hash = crypto.createHash('sha256').update(scriptContent).digest('base64');
// CSP header:
Content-Security-Policy: script-src 'self' 'sha256-${hash}';
// HTML:
<script>console.log('Static inline script');</script>