🔌 stew/js
The stew/js package serves as a bridge between the Go/Wasm runtime and the browser's JavaScript environment, allowing you to load external libraries and execute ad-hoc JS code.
Execution and Evaluation
Execute raw JavaScript code or evaluate expressions with automatic type conversion.
js.Run(code string)
Executes a raw JS block in global scope.
js.Invoke(fn, ...args)
Calls a global function with arguments.
js.Eval[T](code) (T, error)
Evaluates an expression into a Go type.
js.Global(name) js.Value
Returns a raw JavaScript object.
Dynamic Script Management
The package allows you to asynchronously load external scripts (CDNs), check for their presence, or unload them.
<goscript client>
import "stew/js"
import "stew/io"
loadConfetti := func() {
url := "https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/dist/confetti.browser.js"
if js.IsLoaded(url) {
js.Invoke("confetti")
return
}
js.Load(url, func() {
js.Invoke("confetti")
})
}
cleanup := func() {
js.Unload("https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/dist/confetti.browser.js")
}
</goscript>
Interoperability (Exposing to JS)
You can expose Go functions or variables to make them accessible from the JavaScript world.
<goscript client>
import "stew/js"
import "stew/io"
import "syscall/js"
func init() {
// Expose a Go function to the JS global scope
js.Set("notifyFromJS", js.FuncOf(func(this js.Value, args []js.Value) any {
io.Alert("Called from JS: " + args[0].String())
return nil
}))
}
</goscript>
Abusing stew/js to manipulate the DOM bypasses Stew's reactivity engine. Prefer pure Go libraries or Signals for UI rendering.