Skip to content
  1. LuzineDebug
  2. Web, HTML & CSS
  3. Refused to execute inline script because it viol…
Web, HTML & CSS Intermediate ≈ 20 min to fix

Fix "Refused to execute inline script because it violates the following Content Security Policy directive"

Error message
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-…'), or a nonce ('nonce-...') is required to enable inline execution.
  • Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self'".
  • Refused to load the script 'https://cdn.example.com/lib.js' because it violates the following Content Security Policy directive: "script-src 'self'".
  • Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'".
  • Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'".
  • Content-Security-Policy: The page’s settings blocked an inline script (script-src-elem) from being executed because it violates the following directive: “script-src 'self'”
In short

The page Content Security Policy only allows scripts loaded from files on your domain (script-src 'self'), so the browser blocks every <script> written in the HTML and every onclick attribute. Move the code to a .js file, or allow that specific script with a nonce or a hash; only add 'unsafe-inline' as a last resort.

Be the first to confirm this fix

What this error means

The Content Security Policy (CSP) is a set of rules sent by the server (Content-Security-Policy header or <meta> tag) telling the browser which code sources it may run. Inline code is the main target of XSS attacks: an attacker who manages to inject HTML injects precisely a <script> or an onerror=. With script-src 'self', only files served by your origin run; every inline script is refused, unless it carries the random nonce of the request or its SHA digest is listed. Chrome even shows the exact hash to allow in the message.

Common causes

  1. Chrome extension on Manifest V3: the CSP of extension pages (popup.html, options.html) forbids every inline script and cannot be relaxed.
  2. CSP added by the server or a middleware: Helmet (Express), a Laravel security package, the nginx or hosting configuration (Netlify, Vercel, Cloudflare).
  3. Inline event attributes: onclick="", onload="", href="javascript:…", which a nonce does not cover.
  4. Script injected by a tool: a Google Tag Manager, analytics or chat snippet, or a hot-reload script added to the HTML without a nonce.

Step-by-step fix

  1. Find where the CSP comes from

    Look at the response header in DevTools > Network > the page > Headers, or search for a <meta http-equiv="Content-Security-Policy"> tag in the HTML. That is where you will change the rule.

    bash
    curl -sI https://example.com/ | grep -i content-security-policy
  2. Simplest fix: an external file

    Move the code to a file served by your domain and replace the onclick attributes with addEventListener. It is also the only fix in a Chrome MV3 extension.

    xml
    <!-- before -->
    <button onclick="save()">Save</button>
    <script>function save() { /* ... */ }</script>
    
    <!-- after -->
    <button id="save">Save</button>
    <script src="/js/app.js" defer></script>
    
    // /js/app.js
    document.getElementById('save').addEventListener('click', () => {
      // ...
    });
  3. Keep an inline script with a nonce (Laravel)

    A nonce is a random value generated on each request, added to the CSP and to each allowed <script>. Laravel handles it with Vite::useCspNonce(); the tags generated by @vite then get the nonce automatically.

    php
    // app/Http/Middleware/AddContentSecurityPolicy.php
    use Closure;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Vite;
    use Symfony\Component\HttpFoundation\Response;
    
    public function handle(Request $request, Closure $next): Response
    {
        Vite::useCspNonce();
    
        return $next($request)->withHeaders([
            'Content-Security-Policy' => "script-src 'self' 'nonce-".Vite::cspNonce()."'",
        ]);
    }
    
    // In a Blade view
    <script nonce="{{ Vite::cspNonce() }}">
        window.appConfig = @json($config);
    </script>
  4. Nonce with Express and Helmet

    Generate the nonce in a middleware placed before Helmet, then reuse it in your template (res.locals.cspNonce).

    javascript
    import crypto from 'node:crypto';
    import helmet from 'helmet';
    
    app.use((req, res, next) => {
      res.locals.cspNonce = crypto.randomBytes(16).toString('base64');
      next();
    });
    
    app.use(helmet({
      contentSecurityPolicy: {
        directives: {
          scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
        },
      },
    }));
  5. Static script: allow its hash

    For an inline script that never changes (static site), add its base64 SHA-256 digest to the directive. Chrome shows the expected hash in the message; otherwise compute it on the exact content between <script> and </script>, whitespace included.

    bash
    printf '%s' "console.log('hello');" | openssl dgst -sha256 -binary | openssl base64
    
    # Content-Security-Policy: script-src 'self' 'sha256-<hash printed above>'
  6. Last resort only: unsafe-inline

    'unsafe-inline' allows every inline script, including those an attacker would inject: the CSP then no longer protects against XSS. If you must use it temporarily, limit it to the affected pages and plan the move to a nonce.

Did this fix work for you?

Confirm it in one click: it will rise for the next developers stuck on the same error.

Keep it from coming back

  • Do not write JavaScript in HTML attributes: attach events from your JS files.
  • Test a new CSP with Content-Security-Policy-Report-Only: the browser reports violations without blocking anything.
  • For dynamically loaded third-party scripts (GTM), combine a nonce with 'strict-dynamic' instead of a long list of domains.

Frequently asked questions

Why do I get this error in my Chrome extension popup?

Manifest V3 enforces script-src 'self' on extension pages and rejects 'unsafe-inline'. Put all the code in popup.js, loaded with <script src="popup.js">, and use addEventListener instead of onclick.

Does a nonce work for onclick?

No. Nonces only apply to <script> tags. Inline handlers require 'unsafe-hashes' with their hash, which is discouraged: replace them with addEventListener.

I did not configure any CSP, where does it come from?

From a middleware (Helmet enables it by default), the web server, the host, a security plugin or a <meta> tag added by a template. The Network tab shows the received header.

Useful tools for this error

More Web, HTML & CSS errors

All Web, HTML & CSS errors →