- Published on
GA4の計測がCSPに弾かれてしまうのを防ぐ
- Authors
- Name
- nisyuu (にしゅう)
- @nishilyuu
本ブログにGA4の設定をしたところ、Content Security Policy(以下CSP)にブロックされてGA4の計測ができずエラーが起きました。
先に対処方法を紹介すると、HTTPのレスポンスヘッダーでこのような指定をする必要があります。
Content-Security-Policy: default-src 'self' https://*.googletagmanager.com;
img-src: https://*.google-analytics.com https://*.googletagmanager.com;
connect-src: https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com
CSPにブロックされていた際、こちらのエラーがブラウザに出力されていました。
Refused to load the script 'https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxxx' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-eval' 'unsafe-inline' giscus.app analytics.umami.is". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
上記はChromeブラウザでのエラーですが、Safariだとこのようなエラーが出ていました。
Unrecognized Content-Security-Policy directive 'www.googletagmanager.com/gtag/js'.
Refused to load https://www.googletagmanager.com/gtag/js?id=G-HTLVF1SN81 because it does not appear in the script-src directive of the Content Security Policy. (x2)