Packages
phoenix_cap
0.1.0
Self-hosted Cap CAPTCHA for Phoenix controllers and LiveView with a bundled WebAssembly solver
Current section
Files
Jump to
Current section
Files
guides/javascript.md
# JavaScript and LiveView hooks
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.
```heex
<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.
```javascript
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.
```elixir
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.
```heex
<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.
```javascript
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.
```javascript
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.
```elixir
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](https://hexdocs.pm/phoenix_live_view/js-interop.html).
## Widget events and methods
Listen on the `<phoenix-cap>` element. The bundled widget dispatches these DOM events.
| Event | Data | When it fires |
| --- | --- | --- |
| `progress` | `detail.progress` | Solver progress as a percentage |
| `solve` | `detail.token` | The server issued a token for this challenge |
| `error` | `detail.code`, `detail.message` | The widget could not solve or redeem the challenge |
| `reset` | No payload required | The 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.
```javascript
await customElements.whenDefined("phoenix-cap")
const { token } = await document.getElementById("confirm-captcha").solve()
```