Skip to content

Instantly share code, notes, and snippets.

@jcdarwin
Last active March 30, 2025 08:52
Show Gist options
  • Save jcdarwin/faf6c6f3842f7c97a62c2a12eda7b5c0 to your computer and use it in GitHub Desktop.
Save jcdarwin/faf6c6f3842f7c97a62c2a12eda7b5c0 to your computer and use it in GitHub Desktop.
How to generate the CSP hash for the script loaded by https://www.googletagmanager.com/gtm.js?id=GTM-KSNK298

What is this?

This is how to generate a hash for use in a script-src CSP header

Why do we need this?

When https://www.googletagmanager.com/gtm.js?id=GTM-KSNK298 loads an inline script, it doesn't correctly include a nonce on the inline script, and so we get a CSP violation and the inline script cannot run.

Hence we need to generate a hash of the inline script and include it in our script-src CSP header.

  • Set a breakpoint in https://www.googletagmanager.com/gtm.js?id=GTM-KSNK298, before the line
    a.insertBefore(g, null));
  • examine the contents of g at the console, and save the contents inside the <script ...> tag (but not the script tag itself) to inline.js
  • if you did this using an editor that adds a trailing newline, you'll need to strip this off:
    echo -n "$(cat ./inline.js | sed '$s/[\r\n]*$//')" > ./inline.js
  • generate the hash of inline.js:
    cat ./inline.js | openssl dgst -sha256 -binary | base64
  • this will give you a hash such as
    S3UiSHOe2qdoi41Y4d87hnve8TTlI5+KYH1tj9ECKLM=
  • add this to your script-src CSP header, being sure to include it inside single quotes and prefixed with sha256-, e.g.
    'sha256-S3UiSHOe2qdoi41Y4d87hnve8TTlI5+KYH1tj9ECKLM='

Note that if the contents of the inline script added by https://www.googletagmanager.com/gtm.js?id=GTM-KSNK298 ever change, then you'll need to regenerate the hash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment