Dstar.Scripts (dstar v0.1.0)

Copy Markdown View Source

Executes JavaScript on the client via SSE.

Appends a <script> tag to the body using datastar-patch-elements.

conn |> execute("alert('Hello!')")
conn |> execute("console.log('debug')", auto_remove: false)

Summary

Functions

Logs a message to the browser console via SSE.

Executes JavaScript on the client by appending a script tag to the body.

Redirects the client to the given URL via JavaScript.

Functions

console_log(conn, message, opts \\ [])

@spec console_log(Plug.Conn.t(), term(), keyword()) :: Plug.Conn.t()

Logs a message to the browser console via SSE.

Options

  • :level - Console method: :log, :warn, :error, :info, :debug (default: :log)
  • Plus all options from execute/3

Examples

conn |> console_log("Debug message")
conn |> console_log("Warning!", level: :warn)
conn |> console_log(%{user: "alice"}, level: :info)

execute(conn, script, opts \\ [])

@spec execute(Plug.Conn.t(), String.t(), keyword()) :: Plug.Conn.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
conn |> execute("alert('Hello!')")

# Keep script in DOM
conn |> execute("window.myVar = 42", auto_remove: false)

# ES module script
conn |> execute("import {...} from 'module'", attributes: %{type: "module"})

redirect(conn, url, opts \\ [])

@spec redirect(Plug.Conn.t(), String.t(), keyword()) :: Plug.Conn.t()

Redirects the client to the given URL via JavaScript.

Uses Jason.encode!/1 to safely encode the URL, preventing injection attacks. Uses setTimeout for proper browser history handling.

Examples

conn |> redirect("/workspaces")
conn |> redirect("https://example.com")