kobweb icon indicating copy to clipboard operation
kobweb copied to clipboard

Allow adding body scripts in a kobweb block (#299)

Open kocheick opened this issue 5 months ago • 3 comments

Overview

This PR adds support for injecting custom <body> elements (such as scripts, meta tags, and other HTML content) directly through the Kobweb application block configuration, enabling developers to add analytics, Bootstrap, and other scripts without modifying HTML templates. Closes #299

What's Changed

  • Added AppBlock.body configuration block for defining custom <body> content in build.gradle.kts
  • Enhanced KobwebGenerateSiteIndexTask to process and inject custom body elements during site generation
  • Added serializeBodyContents utility for creating and serializing custom <body> content blocks
  • Updated IndexTemplate to support custom <body> element injection
  • Added comprehensive logging during index generation for better visibility of injected elements
  • Extended HtmlUtil with body content serialization capabilities

API Usage

Developers can now add custom body content in their build.gradle.kts:

kobweb {
    app {
        index {
            description.set("My awesome Kobweb app")
            
            // Add custom body elements using body.add {}
            body.add {
                script {
                    src = "https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
                    async = true
                }
            }
            
            body.add {
                script {
                    src = "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
                    attributes["integrity"] = "sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
                    attributes["crossorigin"] = "anonymous"
                }
            }
            
            body.add {
                script {
                    unsafe {
                        raw("""
                            // Custom analytics or other JavaScript
                            console.log('Custom body script loaded');
                        """.trimIndent())
                    }
                }
            }
        }
    }
}

Use Cases

  • Adding analytics scripts (Google Analytics, Meta Pixel, etc.)
  • Including Bootstrap or other CSS/JS frameworks that need body injection
  • Injecting custom scripts that need to be placed in the <body> tag
  • Adding meta tags or other HTML content that belongs in the document body
  • Supporting third-party integrations that require specific script placement

Implementation Details

  • File Changes: 5 files modified across the application plugin
  • Backward Compatibility: Fully backward compatible - no breaking changes
  • Build Integration: Seamlessly integrates with existing Kobweb build process
  • Template System: Leverages existing index template generation infrastructure
  • API Design: Uses body.add {} blocks for adding multiple body elements

Testing

  • ✅ Tested with Bootstrap integration
  • ✅ Tested with analytics script injection
  • ✅ Verified proper HTML serialization and template integration
  • ✅ Confirmed logging output during site generation
  • ✅ Validated backward compatibility with existing projects

Breaking Changes

None - this is a purely additive feature that maintains full backward compatibility.

kocheick avatar Aug 22 '25 17:08 kocheick

You're right, I'll be happy to switch back. I intended to do a fix which consists of exposing body {...} instead of body.add {...}, I ended up getting carried away and added those bodyTargets. I do believe the initial PR suffice enough until we get more requests/feedbacks from users

kocheick avatar Aug 25 '25 22:08 kocheick

Yes, please switch back. I don't want to add extra code that we don't even know if anyone needs.

All I wanted was a discussion to ensure that we weren't painting ourselves into a corner.

bitspittle avatar Aug 26 '25 16:08 bitspittle

All should be good, feel free to review the overall changes and let me know if there are any updates needed

kocheick avatar Sep 04 '25 13:09 kocheick