How do you fix "Refused to load the script because it violates Content Security Policy"? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you fix "Refused to load the script because it violates Content Security Policy"?

message-square
0

To fix "Refused to load the script because it violates Content Security Policy", inspect the browser console error to identify which CSP directive (script-src, script-src-elem, or default-src) blocked the script and which source or inline script violated it, then either allowlist the exact trusted origin or per-request cryptographic nonce in your Content-Security-Policy header (or remove/externalize disallowed inline scripts and eval()-style code rather than weakening security with overly broad wildcards or 'unsafe-inline'/'unsafe-eval' unless strictly justified)—validating policy rules, directive entries, and violation reports safely with typeof / instanceof checks, a Map, and try / catch blocks.


1. Building and Validating a Safe Content-Security-Policy (script-src) Header with a Map

When configuring a Content Security Policy (CSP) in Node/Express, build directives inside a Map so dynamic directives and allowlists never collide with Object.prototype properties, and validate every source token inside try / catch:

// Build a validated Content-Security-Policy header string from a Map of directives
function buildContentSecurityPolicyHeader(directivesMap) {
  if (!(directivesMap instanceof Map)) {
    throw new TypeError("Expected directivesMap to be a Map instance.");
  }

  try {
    const policyParts = [];

    for (const [directiveName, sourcesList] of directivesMap.entries()) {
      if (typeof directiveName !== "string" || directiveName.trim().length === 0) {
        throw new TypeError("Expected every CSP directive name to be a non-empty string.");
      }
      if (!Array.isArray(sourcesList)) {
        throw new TypeError(`Expected sources for directive "${directiveName}" to be an Array.`);
      }

      const cleanDirective = directiveName.trim();
      const cleanSources = [];

      for (const sourceToken of sourcesList) {
        if (typeof sourceToken !== "string" || sourceToken.trim().length === 0) {
          throw new TypeError(`Invalid source token in directive "${cleanDirective}".`);
        }
        const trimmedToken = sourceToken.trim();
        if (trimmedToken === "*") {
          throw new Error(`Wildcard "*" is not allowed in directive "${cleanDirective}".`);
        }
        cleanSources.push(trimmedToken);
      }

      policyParts.push(
        cleanSources.length > 0 ? `${cleanDirective}${cleanSources.join(" ")}` : cleanDirective
      );
    }

    return policyParts.join("; ");
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed building Content-Security-Policy header: ${message}`);
  }
}

// Example usage:
// try {
//   const cspMap = new Map([
//     ["default-src", ["'self'"]],
//     ["script-src", ["'self'", "https://cdn.example.com", "'nonce-r4nd0mV4lu3'"]],
//     ["object-src", ["'none'"]],
//     ["base-uri", ["'self'"]]
//   ]);
//   const headerValue = buildContentSecurityPolicyHeader(cspMap);
//   console.log("CSP Header:", headerValue);
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Check the exact blocked URI/directive in the browser console: Console messages show the violated directive (such as script-src-elem) and the blocked URL or 'inline' script source.
  • Avoid 'unsafe-inline' for scripts when nonces or hashes work: A fresh per-response cryptographic nonce on <script nonce="..."> and in script-src 'nonce-...' protects against injected inline scripts.

2. Parsing CSP Violation Reports or Blocked Script Origins into a Map

When auditing CSP script blocks across pages, third-party embeds, or browser extensions, normalize violation details into a Map inside try / catch so dynamic keys never collide with Object.prototype properties:

// Normalize a CSP violation or console error record into a Map for diagnostics
function inspectCspScriptViolation(reportInput) {
  if (typeof reportInput !== "object" || reportInput === null || Array.isArray(reportInput)) {
    throw new TypeError("Expected reportInput to be a non-null diagnostic object.");
  }

  try {
    const blockedUri = typeof reportInput.blockedUri === "string"
      ? reportInput.blockedUri.trim()
      : "";
    const violatedDirective = typeof reportInput.violatedDirective === "string"
      ? reportInput.violatedDirective.trim()
      : "script-src";
    const sourceFile = typeof reportInput.sourceFile === "string"
      ? reportInput.sourceFile.trim()
      : "";

    const isExtensionBlocked = blockedUri.startsWith("chrome-extension://") ||
      blockedUri.startsWith("moz-extension://") ||
      blockedUri.startsWith("edge-extension://");

    return new Map([
      ["violatedDirective", violatedDirective],
      ["blockedUri", blockedUri || "(inline or unspecified)"],
      ["sourceFile", sourceFile || "(unknown)"],
      ["isBrowserExtension", isExtensionBlocked],
      ["recommendedAction", isExtensionBlocked
        ? "Check if a browser extension injects scripts or test in an Incognito/clean profile"
        : "Allowlist trusted origin/nonce in script-src or move inline script to an external module"]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed inspecting CSP script violation: ${message}`);
  }
}

// Example usage:
// try {
//   const diagMap = inspectCspScriptViolation({
//     violatedDirective: "script-src-elem",
//     blockedUri: "https://analytics.example.com/tag.js",
//     sourceFile: "https://app.example.com/"
//   });
//   console.log("Action:", diagMap.get("recommendedAction"));
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Use Map for diagnostic fields: Prevents Object.prototype collisions on arbitrary report keys.
  • Test in an extension-free / Incognito window first: Browser extensions and injected page scripts frequently trigger script-src violations even when your own app scripts are clean.

3. Common CSP Script Pitfalls (script-src-elem, Nonces, and eval)

Keep these Content Security Policy details in mind when troubleshooting blocked scripts:

  • script-src-elem vs. script-src: Modern browsers evaluate external <script src="..."> and inline <script> elements against script-src-elem if present (falling back to script-src, then default-src).
  • Nonces must be unique per HTTP response and match <script nonce="...">: Reusing a static nonce across requests defeats nonce protection; generating a new random value per response keeps it effective.
  • Avoid 'unsafe-eval' unless required by legacy code: Dynamic code evaluation (eval(), new Function(), string timers) is blocked unless explicitly allowed—refactor to standard functions or JSON parsing where possible.