Problem/Motivation
The GleapBlock.php was outputting the Gleap initialization script as an inline
tag directly in the rendered HTML:$script = Markup::create('<script>!function(Gleap,t,i){if(!(Gleap=window.Gleap=window.Gleap||[]).invoked){...Gleap.initialize("' . $this->configFactory->get('gleap_api_key') . '")}}();</script>');
This approach violates the Content Security Policy (CSP) script-src-elem directive, which restricts inline JavaScript execution to prevent Cross-Site Scripting (XSS) attacks. When CSP is enabled without 'unsafe-inline', the browser blocks the inline script from executing, causing Gleap to fail to load.
Steps to reproduce
Enable Gleap module and remove the 'unsafe-inline' from the script-src directive.Proposed resolution
Refactor the module to use an external JavaScript file with Drupal's settings API:- Create
/js/gleap.js- Move the Gleap initialization logic to an external JS file that reads the API key fromdrupalSettings.gleap.apiKey. - Create
/gleap.libraries.yml- Define the library with dependencies oncore/drupalandcore/drupalSettings. - Update
/gleap.module- Addshow_messageandmessagevariables to the theme definition for conditional messaging. - Update /src/Plugin/Block/GleapBlock.php - Instead of outputting inline script:
- Attach the gleap/gleap library
- Pass the API key via drupalSettings
- Use a flag (
show_message) to conditionally display admin messages
- Update
/templates/gleap-block-template.html.twig- Render only the admin message when needed; the JS library handles Gleap initialization.
Benefits
- CSP Compliant: No inline scripts, fully compatible with strict CSP policies
- Security: Eliminates need for
'unsafe-inline'inscript-src-elem - Drupal Best Practices: Uses Drupal's library and settings system properly
- Cacheable: External JS files can be cached by browsers and CDNs
Remaining tasks
- ✅ File an issue
- ✅ Addition/Change/Update/Fix
- ✅ Testing to ensure no regression
- ➖ Automated unit testing coverage
- ➖ Automated functional testing coverage
- ➖ UX/UI designer responsibilities
- ➖ Readability
- ➖ Accessibility
- ✅ Performance
- ✅ Security
- ➖ Documentation
- ✅ Code review by maintainers
- ✅ Full testing and approval
- ✅ Credit contributors
- ✅ Review with the product owner
- ✅ Release notes snippet
- ✅ Release gleap-1.0.5
API changes
- N/A
Data model changes
- N/A
Release notes snippet
- fix: #3569476 Inline Script Violates Content Security Policy (CSP) script-src-elem Directive - By: mohammad-fayoumi
Issue fork gleap-3569476
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #3
mohammad-fayoumiComment #6
rajab natshahComment #7
rajab natshahComment #9
rajab natshah✅ Released gleap-1.0.5