JavaScript and LiveView hooks

Copy Markdown View Source

Inside a form, the widget submits a hidden cap-token field and needs no application JavaScript. A widget outside its form can use form="form-id". Use the examples below when solving a standalone widget should trigger the action immediately. Both assume the root layout loads <PhoenixCap.Components.assets />.

Send a token to a controller

Render the widget and a status message in a controller template.

<PhoenixCap.Components.widget id="confirm-captcha" />
<p id="confirm-status" role="status"></p>

Run this code once after the page markup is available, for example in a deferred application script. Phoenix's root layout supplies the CSRF meta tag.

const widget = document.getElementById("confirm-captcha")

if (widget) {
  const status = document.getElementById("confirm-status")
  const csrf = document.querySelector('meta[name="csrf-token"]').content

  widget.addEventListener("solve", async ({ detail: { token } }) => {
    try {
      const response = await fetch("/confirm", {
        method: "POST",
        headers: { "content-type": "application/json", "x-csrf-token": csrf },
        body: JSON.stringify({ "cap-token": token })
      })
      status.textContent = response.ok ? "Confirmed." : "Please verify again."
    } catch {
      status.textContent = "Could not reach the server. Please try again."
    } finally {
      widget.reset()
    }
  })
}

Add the protected action to your app's browser scope, for example post "/confirm", ConfirmationController, :create. The controller plug checks the token before the action executes and responds with HTTP 422 when verification fails.

defmodule MyAppWeb.ConfirmationController do
  use MyAppWeb, :controller
  use PhoenixCap, only: [:create]

  def create(conn, _params) do
    # Perform the protected operation here.
    send_resp(conn, 204, "")
  end
end

Send a token to a LiveView

Attach a hook to the widget when your LiveView handles the action without a form. The example uses the LiveView flash to display the result.

<PhoenixCap.Components.widget id="live-confirm-captcha" phx-hook="CapConfirm" />

Create assets/js/hooks/cap_confirm.js. Read the token from the event, then reset the widget when the server replies. Removing the listener in destroyed lets LiveView unmount and remount the widget cleanly.

export const CapConfirm = {
  mounted() {
    this.onSolve = ({ detail: { token } }) => {
      this.pushEvent("cap_confirm", { "cap-token": token }, () => {
        if (this.el.isConnected) this.el.reset()
      })
    }
    this.el.addEventListener("solve", this.onSolve)
  },

  destroyed() {
    this.el.removeEventListener("solve", this.onSolve)
  }
}

In assets/js/app.js, import the hook and add it to the options of your existing LiveSocket. This example preserves Phoenix's colocated hooks. If your app has its own hooks object, add CapConfirm to that object.

import { CapConfirm } from "./hooks/cap_confirm"

const csrfToken = document.querySelector('meta[name="csrf-token"]').content
const liveSocket = new LiveSocket("/live", Socket, {
  params: { _csrf_token: csrfToken },
  hooks: { ...colocatedHooks, CapConfirm }
})
liveSocket.connect()

Use the socket as the verification context. The reply triggers the JavaScript callback so a fresh token can be obtained for the next action.

def handle_event("cap_confirm", params, socket) do
  case PhoenixCap.verify(socket, params["cap-token"]) do
    :ok ->
      # Perform the protected operation here.
      {:reply, %{}, put_flash(socket, :info, "Confirmed.")}

    {:error, _reason} ->
      {:reply, %{}, put_flash(socket, :error, "Please verify again.")}
  end
end

Use one server-side check per operation. A form submit handler and a hook that both verify the same token would consume it twice. For hook lifecycle and reply callbacks, see Phoenix LiveView JavaScript interoperability.

Widget events and methods

Listen on the <phoenix-cap> element. The bundled widget dispatches these DOM events.

EventDataWhen it fires
progressdetail.progressSolver progress as a percentage
solvedetail.tokenThe server issued a token for this challenge
errordetail.code, detail.messageThe widget could not solve or redeem the challenge
resetNo payload requiredThe widget cleared its current state. Listen directly on the widget.

To start a solve from your own button, wait for the web component to load and call solve(). It returns a promise and can reject on failure. reset() clears the widget and its hidden form field. It is useful after a request completes when the same widget stays on screen.

await customElements.whenDefined("phoenix-cap")
const { token } = await document.getElementById("confirm-captcha").solve()