Is there a good way to add javascript (one file, minimized) to a theme component so that it can be used in common/header.html?
AI-generated summary
Users are discussing how to add JavaScript to a Discourse theme component. sbernhard initially asked how to add a minimized JavaScript file to a theme component, but ended up adding the non-minimized JavaScript directly to common/header.html instead sbernhard.
Amethi is trying to use custom JavaScript in the Versatile Banner component, but is encountering a Content Security Policy (CSP) error when attempting to call the JavaScript function via an inline onclick event handler. After further research, Amethi found a potential solution related to the CSP policy.
fzngagan suggested using the loadScript method from the Discourse codebase as a systematic way to achieve this.
Got it working. Just added the JS (not minimized) into the common/header.html.
See discourse-highlight-text/common/header.html at master · sbernhard/discourse-highlight-text · GitHub
Would be good if someone could document this behavior to the theme /component developer guide.
How did you use the JS in your component? I’m using the Versatile Banner component and want to add a button that calls my custom JS function. I’ve put in the head as you mention but get a CSP error:
dev.londonbikers.com/:1 Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src https://dev.londonbikers.com/logs/ https://dev.londonbikers.com/sidekiq/ https://dev.londonbikers.com/mini-profiler-resources/ https://dev.londonbikers.com/assets/ https://dev.londonbikers.com/brotli_asset/ https://dev.londonbikers.com/extra-locales/ https://dev.londonbikers.com/highlight-js/ https://dev.londonbikers.com/javascripts/ https://dev.londonbikers.com/plugins/ https://dev.londonbikers.com/theme-javascripts/ https://dev.londonbikers.com/svg-sprite/". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
When calling my code via onclick="NavigateToCustomLoginUrl('facebook')" on a button.
Oh, think I answered my own question via Content security policy | Articles | web.dev
Check loadScript in the codebase/meta for a systematic way to achieve this.