Functions for executing JavaScript on the client.
This module provides utilities for sending JavaScript to execute in the browser through Server-Sent Events.
Internally, this uses datastar-patch-elements to append a <script> tag
to the body, which is the approach used by the official Datastar SDKs.
Executing Scripts
Send JavaScript to run on the client:
sse
|> PhoenixDatastar.Scripts.execute("alert('Hello!')")
# Keep script tag in DOM (default auto-removes after execution)
sse
|> PhoenixDatastar.Scripts.execute("console.log('debug')", auto_remove: false)
# With script attributes (e.g., ES modules)
sse
|> PhoenixDatastar.Scripts.execute("import {...}", attributes: %{type: "module"})Convenience Functions
Common script operations have dedicated helpers:
sse
|> PhoenixDatastar.Scripts.redirect("/dashboard")
sse
|> PhoenixDatastar.Scripts.console_log("Debug info", level: :warn)
Summary
Functions
Logs a message to the browser console.
Executes JavaScript on the client by appending a script tag to the body.
Redirects the browser to a new URL.
Functions
@spec console_log(PhoenixDatastar.SSE.t(), term(), keyword()) :: PhoenixDatastar.SSE.t()
Logs a message to the browser console.
Options
:level- Console method to use::log,:warn,:error,:info,:debug(default: :log)- Plus all options from
execute/3
Examples
sse |> console_log("Debug message")
sse |> console_log("Warning!", level: :warn)
sse |> console_log(%{user: "alice", action: "login"}, level: :info)
@spec execute(PhoenixDatastar.SSE.t(), String.t(), keyword()) :: PhoenixDatastar.SSE.t()
Executes JavaScript on the client by appending a script tag to the body.
Options
:auto_remove- Remove script tag after execution (default: true):attributes- Map of additional script tag attributes:event_id- Event ID for client tracking:retry- Retry duration in milliseconds
Examples
# Simple script execution
sse |> execute("alert('Hello!')")
# Keep script in DOM
sse |> execute("window.myVar = 42", auto_remove: false)
# ES module script
sse |> execute("import {...} from 'module'", attributes: %{type: "module"})
@spec redirect(PhoenixDatastar.SSE.t(), String.t(), keyword()) :: PhoenixDatastar.SSE.t()
Redirects the browser to a new URL.
Options
Same as execute/3.
Examples
sse |> redirect("/dashboard")
sse |> redirect("https://example.com")