How to add analytics and pixel scripts avoiding Content Security Policy (XSS)

AI-generated summary

Adding Analytics and Pixel Scripts while Avoiding Content Security Policy (XSS)

illusionandcards is trying to add Facebook Pixel and Posthog analytics scripts to their site, but is encountering issues due to Content Security Policy (CSP). Despite attempting to hash the script and adding “unsafe-eval” to the scripts src, the issue persists.

jericson suggests that CSP might not be the problem, as they were able to add PostHog to their site without changing any CSP settings. They recommend adding one script at a time, starting with PostHog, and checking if it works. jericson also provides a link to a theme component that can be used to add PostHog to a Discourse site.

Additionally, jericson mentions that the PostHog toolbar doesn’t work out of the box with Discourse and provides a link to the PostHog documentation for troubleshooting.

Good day,

I’ve tried to add the Facebook Pixel script and Posthog analytics to my site with a custom component and editing the html from the default theme.

These are not working because of Content Security Policy. I even tried hashing the script with sha256, but I get this error when adding it to “content security policy script src”:

I’ve also read this topic: Mitigate XSS Attacks with Content Security Policy

How can I avoid CSP on specific scripts?

Thank you!

I’ve even disabled the Content Security Policy and added “unsafe-eval” con scripts src, but it’s still not working.

Here is my custom component (in the head):

I recently added PostHog to several sites and didn’t need to change any CSP settings. (I haven’t tried Facebook Pixel. It might help to add one thing at a time.) My technique was to use a Theme Component:

That’s a strong signal CSP isn’t the problem.

Try starting with just PostHog in the beginning and see if that works. If it does, try just Meta Pixel.

For what it’s worth, the PostHog toolbar doesn’t work out of the box with Discourse. See: