> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://statpad.dev/docs/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://statpad.dev/docs/_mcp/server.

# Hosted pages

> Load Statpad's embed widgets in an iframe on a site that can't run scripts, or in an iOS, Android or React Native WebView, and receive their height, select and open messages.

A hosted page is one widget on a page of its own, served by Statpad at `embed.statpad.dev`. Use one where the [script tag](/docs/embeds#quickstart) can't go:

* **In a mobile app**, load it in a WebView.
* **On a site whose editor strips scripts**, such as some CMSes, put it in an iframe.

On a site that can run scripts, use the script tag instead. It sizes itself, uses your page's font and needs no extra settings on the key.

## URLs

| Widget     | URL                                       |
| ---------- | ----------------------------------------- |
| Scoreboard | `https://embed.statpad.dev/v1/scoreboard` |
| Scores     | `https://embed.statpad.dev/v1/scores`     |

The query string takes `key` and the element's [attributes](/docs/embeds/elements):

| Page             | Parameters                                                             |
| ---------------- | ---------------------------------------------------------------------- |
| `/v1/scoreboard` | `key`, `league`, `game`, `variant`, `theme`, `accent`, `surface`       |
| `/v1/scores`     | `key`, `league`, `date`, `layout`, `max`, `theme`, `accent`, `surface` |

```text
https://embed.statpad.dev/v1/scoreboard?key=statpad_pk_...&league=nfl&game=GAME_ID
https://embed.statpad.dev/v1/scores?key=statpad_pk_...&league=nfl&layout=strip&accent=%23C8102E
```

Replace `GAME_ID` with a game's id, which you get the same way as for the script tag: from a scores page's `statpad:select` message ([Messages](#messages)), or from `GET /v1/{league}/games` in the REST API. Encode the `#` of an `accent` as `%23`. Otherwise the browser reads the colour as the URL's fragment and the widget gets no accent. The page renders the widget edge to edge in the system font.

The **Embeds** page of your account builds these URLs for each key under **Mobile apps and iframes**.

## Turn them on for a key

A key serves hosted pages only where you allow them. Edit the key on the **Embeds** page and turn on one or both switches under **Hosted pages**:

| Switch                     | Lets the page load                    | Any other site or app                             |
| -------------------------- | ------------------------------------- | ------------------------------------------------- |
| **Iframes on these sites** | In an iframe on the key's own origins | Can't frame it. The browser refuses to render it. |
| **Mobile apps**            | Top-level, as a WebView loads it      | Can show it too, if it has the key                |

With both off, no load is allowed. A change reaches new page loads within a few minutes.

> **Warning**
>
> Apps send no origin that Statpad can check. So with **Mobile apps** on, any app, or any browser tab opened at the URL, can show the key's widgets, and the key's origins don't restrict that. Its widgets show only what your pages already show publicly, and they cost you nothing but view-count accuracy. Use a separate key for your apps, so you can revoke it without touching your websites.

### When a load isn't allowed

What you see depends on where the page loads:

* **In an iframe**, the browser blocks the frame and shows its own blank or error frame instead of the widget. That happens when the framing site isn't on the key's origins, when **Iframes on these sites** is off, when the key is unknown or revoked, and when Statpad can't look the key up. Statpad sends every refusal with a policy that forbids framing it, so no text shows.
* **Top-level**, in an app's WebView or a browser tab, you get a short page of plain text:

| Status | Text                                                         | Fix                                      |
| ------ | ------------------------------------------------------------ | ---------------------------------------- |
| `404`  | This embed key doesn't exist.                                | Copy the key again from the Embeds page. |
| `403`  | This embed key has been revoked.                             | Create a new key.                        |
| `403`  | This embed key doesn't allow its widgets in apps.            | Turn on **Mobile apps**.                 |
| `503`  | This widget can't be shown right now. Try again in a moment. | Reload later.                            |

To see why an iframe stays blank, check the browser console, which names the blocked frame. Opening the iframe's URL in a browser tab shows the key's problem, unless **Mobile apps** is off, in which case the tab shows the apps refusal instead.

A page that loaded is different: it shows the widget, and if a later [check](#when-the-key-changes) refuses it, the widget replaces the game with a message, such as **Embed key revoked**.

## In an iframe

```html
<iframe
  src="https://embed.statpad.dev/v1/scoreboard?key=statpad_pk_...&amp;league=nfl&amp;game=GAME_ID"
  title="Scoreboard"
  style="width:100%;height:500px;border:0"
  loading="lazy"
></iframe>
```

The page must be framed by one of the key's origins. In a page nested inside another frame, every frame above it must be on the key's origins too.

A site that can't run scripts can't resize the frame, so give it a fixed height:

| Widget                 | Height                                           |
| ---------------------- | ------------------------------------------------ |
| Scoreboard             | 500px, enough for a live game with its last play |
| Scores, `layout=list`  | 640px, about six games. It scrolls past that.    |
| Scores, `layout=strip` | 120px                                            |

Where your page can run a script, size the frame to its content with the `statpad:height` message:

```html
<script>
  addEventListener("message", (e) => {
    if (e.origin !== "https://embed.statpad.dev" || e.data?.type !== "statpad:height") return;
    for (const frame of document.querySelectorAll("iframe")) {
      if (frame.contentWindow === e.source) frame.style.height = `${e.data.height}px`;
    }
  });
</script>
```

### Referrer-Policy

A framed page checks which sites are framing it, and a restrictive referrer policy on a framing page can hide that page's origin. Most browsers tell the widget every frame above it, but they can hide a frame's origin when that frame sends `Referrer-Policy: no-referrer` or `same-origin`, and the check then fails with **Not available on this site**. A browser that lists no frames leaves the widget only the referrer, the address of the page directly above it. There, the same policies, or an iframe with `referrerpolicy="no-referrer"`, leave the widget unable to name the site, and it shows **Not available on this site** with the line "This page can't confirm which site is embedding it, so it can't check that site is allowed."

To fix it, send a policy that keeps the origin, such as the browser default, `strict-origin-when-cross-origin`, on the pages that frame the widget, and don't set `referrerpolicy` on the iframe. Or use the script tag, which doesn't depend on the referrer.

## Messages

A hosted page tells whatever hosts it what's happening, with three messages:

| `type`           | Fields                    | When                                                         |
| ---------------- | ------------------------- | ------------------------------------------------------------ |
| `statpad:height` | `height`, in CSS pixels   | The widget's height changes, including when it first renders |
| `statpad:select` | `game`, `league`, `state` | A reader taps a game in a scores page                        |
| `statpad:open`   | `url`                     | A reader taps the **Powered by Statpad** link inside an app  |

A `statpad:select`, with the recorded Bills at Vikings game from [Sample responses](/docs/replay). That id belongs to the sample data, so it won't load in a widget:

```json
{ "type": "statpad:select", "game": "01a1d60f-67be-7bdd-83f4-53286521d9bb", "league": "nfl", "state": "final" }
```

`state` is the game's [widget state](/docs/embeds/elements#states-and-messages), such as `live` or `final`.

Each message goes to every listener that's there:

| Host                      | Where the message arrives                         | Format        |
| ------------------------- | ------------------------------------------------- | ------------- |
| A web page with an iframe | `message` events on the parent window             | The object    |
| iOS `WKWebView`           | A `WKScriptMessageHandler` named `statpad`        | The object    |
| Android `WebView`         | `postMessage` on an object named `StatpadAndroid` | A JSON string |
| React Native `WebView`    | `onMessage`                                       | A JSON string |

In an app with a listener, tapping the link sends `statpad:open` and the page doesn't navigate, so your app can open the URL in the browser. In an iframe, or in an app with no listener, the link opens as usual. The link is `https://statpad.dev/` with a query string.

## In a mobile app

Turn on **Mobile apps** for the key, then load the hosted page's URL in a WebView and listen for the messages.

Give the widget a WebView of its own, and keep it on `https://embed.statpad.dev`. Anything a page in that WebView can run can call your listener, so the examples below:

* refuse navigation to any other origin, so no other content loads there
* accept messages only from `https://embed.statpad.dev`
* open a `statpad:open` URL only when it's `https` on `statpad.dev`

**`iOS`**

```swift iOS
import UIKit
import WebKit

final class StatpadBridge: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
  var onHeight: (CGFloat) -> Void = { _ in }
  var onSelect: (_ game: String, _ league: String) -> Void = { _, _ in }

  func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) {
    let origin = message.frameInfo.securityOrigin
    guard origin.protocol == "https", origin.host == "embed.statpad.dev", origin.port == 0,
          let m = message.body as? [String: Any], let type = m["type"] as? String else { return }
    switch type {
    case "statpad:height":
      if let height = m["height"] as? Double { onHeight(CGFloat(height)) }
    case "statpad:select":
      if let game = m["game"] as? String, let league = m["league"] as? String { onSelect(game, league) }
    case "statpad:open":
      if let s = m["url"] as? String, let url = URL(string: s), url.scheme == "https", url.host == "statpad.dev" {
        UIApplication.shared.open(url)
      }
    default:
      break
    }
  }

  // Keep the web view on the hosted pages.
  func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    let url = action.request.url
    decisionHandler(url?.scheme == "https" && url?.host == "embed.statpad.dev" ? .allow : .cancel)
  }
}

let bridge = StatpadBridge()
let config = WKWebViewConfiguration()
config.userContentController.add(bridge, name: "statpad")

let webView = WKWebView(frame: .zero, configuration: config)
webView.navigationDelegate = bridge
let heightConstraint = webView.heightAnchor.constraint(equalToConstant: 500)
heightConstraint.isActive = true
bridge.onHeight = { heightConstraint.constant = $0 }

webView.load(URLRequest(url: URL(string: "https://embed.statpad.dev/v1/scoreboard?key=statpad_pk_...&league=nfl&game=GAME_ID")!))
```

**`Android`**

```kotlin Android
import android.content.Intent
import android.net.Uri
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.webkit.WebViewCompat
import androidx.webkit.WebViewFeature
import org.json.JSONObject

const val STATPAD_ORIGIN = "https://embed.statpad.dev"

// Builds the hosted page's URL itself, so the web view loads only embed.statpad.dev.
// widget is "scoreboard" or "scores"; params are the page's other query parameters.
fun WebView.showStatpad(key: String, widget: String, params: Map<String, String>) {
  require(widget == "scoreboard" || widget == "scores")
  val url = Uri.Builder().scheme("https").authority("embed.statpad.dev").path("/v1/$widget")
    .appendQueryParameter("key", key)
    .apply { params.forEach { (k, v) -> appendQueryParameter(k, v) } }
    .build()
  settings.javaScriptEnabled = true

  // Keep the web view on the hosted pages.
  webViewClient = object : WebViewClient() {
    override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
      val u = request.url
      return !(u.scheme == "https" && u.host == "embed.statpad.dev")
    }
  }

  // StatpadAndroid exists only in pages from STATPAD_ORIGIN, and its messages arrive on the UI thread.
  if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
    WebViewCompat.addWebMessageListener(this, "StatpadAndroid", setOf(STATPAD_ORIGIN)) { _, message, _, _, _ ->
      val m = JSONObject(message.data ?: return@addWebMessageListener)
      when (m.optString("type")) {
        "statpad:height" -> {
          val px = (m.getInt("height") * resources.displayMetrics.density).toInt()
          layoutParams = layoutParams.apply { height = px }
        }
        "statpad:select" -> { /* m.getString("game"), m.getString("league") */ }
        "statpad:open" -> {
          val link = Uri.parse(m.getString("url"))
          if (link.scheme == "https" && link.host == "statpad.dev") context.startActivity(Intent(Intent.ACTION_VIEW, link))
        }
      }
    }
  }
  loadUrl(url.toString())
}
```

**`React Native`**

```tsx React Native
import { useState } from "react";
import { Linking } from "react-native";
import { WebView } from "react-native-webview";

const origin = "https://embed.statpad.dev";
// Matches the origin itself, which Android reports, and any URL on it, which iOS reports.
const onEmbed = (url: string) => /^https:\/\/embed\.statpad\.dev(\/|$)/.test(url);

export function Scoreboard({ game }: { game: string }) {
  const [height, setHeight] = useState(500);
  const uri = `${origin}/v1/scoreboard?key=statpad_pk_...&league=nfl&game=${game}`;

  return (
    <WebView
      source={{ uri }}
      style={{ flex: 0, height }}
      originWhitelist={["*"]}
      onShouldStartLoadWithRequest={(r) => onEmbed(r.url)}
      onMessage={(e) => {
        if (!onEmbed(e.nativeEvent.url)) return;
        const m = JSON.parse(e.nativeEvent.data);
        if (m.type === "statpad:height") setHeight(m.height);
        if (m.type === "statpad:open" && /^https:\/\/statpad\.dev(\/|\?|$)/.test(m.url)) Linking.openURL(m.url);
      }}
    />
  );
}
```

On Android, `WebViewCompat` comes from the `androidx.webkit:webkit` library. Unlike `addJavascriptInterface`, its listener exposes `StatpadAndroid` only to pages from the origins you name. Add it before `loadUrl`, because it applies from the next page load. `shouldOverrideUrlLoading` doesn't see the URL your app loads, so the helper builds that URL rather than taking one: `webView.showStatpad("statpad_pk_...", "scoreboard", mapOf("league" to "nfl", "game" to gameId))`.

In React Native, `flex: 0` lets the `height` take effect. `originWhitelist={["*"]}` hands every navigation to `onShouldStartLoadWithRequest`, which allows only the hosted pages. With a narrower whitelist, the WebView would open a URL outside it with `Linking.openURL` before your check runs. A message's `url` is the page's origin on Android and its full address on iOS, so `onEmbed` accepts both.

`height` is in CSS pixels. iOS points and React Native's layout units match them, and Android multiplies by the screen density, as above.

## When the key changes

A hosted page that's already open asks again every 2 minutes, and whenever it's shown after being hidden, whether the key still allows it there. So revoking the key, removing the site's origin, or turning off the switch the page relies on stops open pages within a few minutes. The page then shows why, such as **Embed key revoked**, or **Not available on this site** with a line saying which switch to turn on. A page stopped this way needs a reload after you fix the key.

If those checks can't reach Statpad at all, the page keeps working for 10 minutes, then shows **Score unavailable**.