---
title: "iOS Native Integration for Web Widgets"
canonical_url: "https://docs.sportradar.com/resources/widgets/docs/tutorials/ios-native-integration"
markdown_url: "https://docs.sportradar.com/resources/widgets/docs/tutorials/ios-native-integration.md"
last_updated: "2026-07-27T09:12:12Z"
---

# iOS Native Integration for Web Widgets

This guide explains how to host Sportradar web widgets inside a native iOS app using SwiftUI and `WKWebView`.

The integration pattern is reusable for all widgets. The only widget-specific parts are:

- the widget name passed to `SIR("addWidget", ...)`
- the props object passed to that widget
- optional loader options (language, theme, adapters, and similar)
- optional JavaScript callbacks such as `onTrack` or `onItemClick`

How you assemble the HTML page is up to you. Follow the Sportradar web / JavaScript widget documentation for the loader bootstrap and `SIR("addWidget", ...)` call. On iOS, host that page with `SportradarWidgetView`, which provides layout helpers and JavaScript communication.

## Intended Audience

This tutorial is for:

- **iOS developers** integrating Sportradar web widgets into SwiftUI apps
- **Technical integrators** who already understand basic [widget integration](https://docs.sportradar.com/resources/widgets/docs/tutorials/getting-started.md)
- Developers familiar with `WKWebView`, `UIViewRepresentable`, and JavaScript bridges

## Goals

By completing this tutorial, you will:

- Build a reusable SwiftUI host (`SportradarWidgetView`) around `WKWebView`
- Load Sportradar widget HTML with the correct base URL so assets resolve
- Bridge JavaScript → Swift messages (height and widget callbacks)
- Bridge Swift → JavaScript so you can call `SIR(...)` without reloading
- Size the web view to the widget’s content height inside native scroll containers
- Swap widgets by changing HTML / props only — not the native host

## Prerequisites

Before starting, ensure you have:

- **Xcode** with SwiftUI and WebKit available (system frameworks only — no third-party dependencies)
- **Client ID** — see [how to obtain one](https://docs.sportradar.com/resources/widgets/docs/tutorials/faq.md#client-id)
- **Basic widget integration experience** — completed the [Getting Started](https://docs.sportradar.com/resources/widgets/docs/tutorials/getting-started.md) guide
- **Familiarity with the [SIR API](https://docs.sportradar.com/resources/widgets/docs/tutorials/SIR.md)** (`addWidget`, `updateWidget`, `setClientTheme`, and related methods)
- A valid **match ID** (or other entity ID) for testing

> **Tip**
>
> Dependencies are system frameworks only: `SwiftUI` and `WebKit`.

## Overview

The generic integration flow is:

1. **Build the shared SwiftUI host**

   Implement `SportradarWidgetView` with a message bridge, height observer, and optional JavaScript bridge.

2. **Build the widget HTML page**

   Follow the Sportradar JS widget docs for the `widgetloader` bootstrap and `SIR("addWidget", ...)` call.

3. **Host the page in SwiftUI**

   Pass the HTML into `SportradarWidgetView` and let the page load the loader / call `SIR("addWidget", ...)`.

4. **Handle events and live updates (optional)**

   Receive widget events and height via `srBridge`, and optionally call `SIR(...)` from Swift without reloading.

### What to implement

The following pieces are enough for an iOS integration:

1. The shared SwiftUI host web view: `SportradarWidgetView`
2. Widget HTML built according to Sportradar’s JS documentation
3. Handling of `onMessage` for height and widget callbacks
4. Optionally `onBridgeReady` / `SrJavaScriptBridge` for Swift → JS

> **Note**
>
> You may choose to add code that builds widget HTML from parameters or automatically injects the Sportradar loader bootstrap. Those helpers are useful, but they are not required for a basic implementation.

### Generic vs widget-specific

#### Shared across all widgets

- `SportradarWidgetView` / `SrJavaScriptBridge`
- `srBridge` message handling
- Height reporting and native frame sizing
- Base URL loading behavior

#### Changes per widget

- Widget name
- Props
- Loader options
- Optional callbacks

How you store or generate the HTML is an app concern, not part of the host.

## Building SportradarWidgetView

The steps below walk through recreating `SportradarWidgetView`. Capabilities are added progressively. The [full host reference](#full-host-reference) shows the finished combined implementation. After the host is complete, [Using SportradarWidgetView](#using-sportradarwidgetview) covers widget HTML and consumer usage.

`SportradarWidgetView` is a reusable SwiftUI wrapper around `WKWebView` that should:

- load your HTML with `loadHTMLString` and base URL `https://widgets.sir.sportradar.com/` (so relative loader/assets resolve)
- register a script message handler (this guide uses the name `srBridge`; any name works if Swift and JS agree)
- inject a height `ResizeObserver` and report height through the same handler
- clear the web-view background so the SwiftUI background can show through
- optionally disable web-view scrolling for nested native scroll UIs
- expose `SrJavaScriptBridge` for evaluating JavaScript (Swift → JS)

> **Info**
>
> `srBridge` in these examples is just the JavaScript bridge name exposed by iOS through `WKScriptMessageHandler`. It is **not** a required Sportradar name. You can rename it, as long as the Swift side and JavaScript side use the same name consistently.

### Step 1: Implement a basic WKWebView UIViewRepresentable wrapper

Start with a host that only loads HTML into a `WKWebView`. No bridges yet — just enough to render a Sportradar widget page inside SwiftUI.

```swift
import SwiftUI
import WebKit

struct SportradarWidgetView: UIViewRepresentable {
    let html: String
    let disableScroll: Bool

    private static let baseURL = URL(string: "https://widgets.sir.sportradar.com/")!

    init(html: String, disableScroll: Bool = false) {
        self.html = html
        self.disableScroll = disableScroll
    }

    func makeCoordinator() -> Coordinator {
        Coordinator()
    }

    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView(frame: .zero)
        webView.isOpaque = false
        webView.backgroundColor = .clear
        webView.scrollView.backgroundColor = .clear
        webView.scrollView.isScrollEnabled = !disableScroll
        webView.scrollView.bounces = !disableScroll

        context.coordinator.load(html, into: webView)
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        context.coordinator.load(html, into: webView)
    }

    final class Coordinator {
        private var loadedHTML: String?

        func load(_ html: String, into webView: WKWebView) {
            guard html != loadedHTML else { return }
            loadedHTML = html
            webView.loadHTMLString(html, baseURL: SportradarWidgetView.baseURL)
        }
    }
}
```

**Key points:**

- Use base URL `https://widgets.sir.sportradar.com/` so relative loader/assets resolve correctly
- Clear opacity and backgrounds so the SwiftUI background can show through
- Reload HTML only when the string changes (avoids tearing down the loader on every SwiftUI update)
- Use `disableScroll: true` together with an explicit `.frame(height:)` when embedding inside `NavigationStack`, `ScrollView`, or `List` (see [Step 6](#step-6-host-the-page-in-your-swiftui-ui))

> **Tip**
>
> At this point you can pass widget HTML into `SportradarWidgetView` and see it render. The next steps add communication and auto-height.

### Step 2: Implement a message handler and JS → Swift communication

Register a `WKScriptMessageHandler` so JavaScript can post into Swift via `window.webkit.messageHandlers.srBridge`. Swift forwards each payload to an `onMessage` closure.

This guide chooses:

- the handler name `"srBridge"`
- a `type` key on every payload, with branching on `type` in `onMessage`
- a **single** message handler for all JS → Swift traffic (height in Step 3; widget callbacks in Step 7), to keep the example small

Extend the Step 1 host:

1. Make `Coordinator` conform to `WKScriptMessageHandler`
2. Register the handler on `WKUserContentController` in `makeUIView`
3. Forward `message.body` to an `onMessage` closure
4. Remove the handler in `dismantleUIView` to avoid retain leaks

```swift
struct SportradarWidgetView: UIViewRepresentable {
    static let messageHandlerName = "srBridge"

    let html: String
    let disableScroll: Bool
    var onMessage: ((Any) -> Void)?

    private static let baseURL = URL(string: "https://widgets.sir.sportradar.com/")!

    init(
        html: String,
        disableScroll: Bool = false,
        onMessage: ((Any) -> Void)? = nil
    ) {
        self.html = html
        self.disableScroll = disableScroll
        self.onMessage = onMessage
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(onMessage: onMessage)
    }

    func makeUIView(context: Context) -> WKWebView {
        let configuration = WKWebViewConfiguration()
        configuration.userContentController.add(
            context.coordinator,
            name: Self.messageHandlerName
        )

        let webView = WKWebView(frame: .zero, configuration: configuration)
        webView.isOpaque = false
        webView.backgroundColor = .clear
        webView.scrollView.backgroundColor = .clear
        webView.scrollView.isScrollEnabled = !disableScroll
        webView.scrollView.bounces = !disableScroll

        context.coordinator.load(html, into: webView)
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        context.coordinator.onMessage = onMessage
        context.coordinator.load(html, into: webView)
    }

    static func dismantleUIView(_ uiView: WKWebView, coordinator: Coordinator) {
        uiView.configuration.userContentController
            .removeScriptMessageHandler(forName: messageHandlerName)
    }

    final class Coordinator: NSObject, WKScriptMessageHandler {
        var onMessage: ((Any) -> Void)?
        private var loadedHTML: String?

        init(onMessage: ((Any) -> Void)?) {
            self.onMessage = onMessage
        }

        func load(_ html: String, into webView: WKWebView) {
            guard html != loadedHTML else { return }
            loadedHTML = html
            webView.loadHTMLString(html, baseURL: SportradarWidgetView.baseURL)
        }

        func userContentController(
            _ userContentController: WKUserContentController,
            didReceive message: WKScriptMessage
        ) {
            guard message.name == SportradarWidgetView.messageHandlerName else { return }
            onMessage?(message.body)
        }
    }
}
```

> **Warning**
>
> Always remove the message handler in `dismantleUIView`. Leaving it registered can cause retain cycles and crashes when the view is destroyed.

After this step, JS can send messages into Swift. Widget callbacks still post through the same `srBridge` handler — see [Step 7](#step-7-bridge-widget-callbacks-to-swift) for `onTrack` / `onItemClick` examples.

### Step 3: Add height reporting

Height reporting is necessary so SwiftUI can constrain the web view to the **widget’s actual content height**. Without a reported height, a `WKWebView` in a flexible layout typically expands to fill all available vertical space. That fights nested scroll UIs (`ScrollView`, `List`, `NavigationStack`): you usually want the web view sized to the widget and the *native* container to scroll.

With `disableScroll: true` and `.frame(height: reportedHeight)`, the host matches the widget instead of stretching full-height. Consumer-side sizing is covered in [Step 6](#step-6-host-the-page-in-your-swiftui-ui).

`WKWebView` does not tell SwiftUI how tall its HTML content is, so the page must measure itself and send the value into Swift over `srBridge`. `installHeightObserverJS` is a JavaScript string you inject once via `WKUserScript`. It is not Sportradar-specific API — you write it. The script’s job is:

1. Pick a DOM element whose height represents the widget
2. Measure that element
3. `postMessage` the height through `srBridge`
4. Re-measure whenever the element resizes (widgets grow/shrink as they load or update)

This guide observes `[data-sr-height-root]` and falls back to `document.body` if that attribute is missing. Mark the mount in your widget HTML (see [Step 5](#step-5-build-the-widget-html-from-the-js-docs)):

```html
<div id="sr-widget" data-sr-height-root></div>
```

Keep the widget HTML minimal and let the shared iOS host inject the height observer.

#### Building the script

Construct the script from small pieces:

**1. Resolve the element**

```js
function heightRoot() {
    return document.querySelector("[data-sr-height-root]") || document.body;
}
```

**2. Measure and post** — read layout height and send a JSON-friendly payload Swift can parse (`type: "height"` so `onMessage` can branch like other messages):

```js
function postHeight() {
    var el = heightRoot();
    var height = Math.ceil(el.getBoundingClientRect().height);
    if (height > 0 && window.webkit && window.webkit.messageHandlers.srBridge) {
        window.webkit.messageHandlers.srBridge.postMessage({
            type: "height",
            height: height
        });
    }
}
```

**3. Observe changes** — attach a `ResizeObserver` and post once immediately so Swift gets an initial height:

```js
new ResizeObserver(postHeight).observe(heightRoot());
postHeight();
```

**4. Wrap in an IIFE** — keep locals off `window`:

```js
(function() {
    // heightRoot, postHeight, ResizeObserver…
})();
```

#### Assembled script

```swift
private static let installHeightObserverJS = """
(function() {
    function heightRoot() {
        return document.querySelector("[data-sr-height-root]") || document.body;
    }
    function postHeight() {
        var el = heightRoot();
        var height = Math.ceil(el.getBoundingClientRect().height);
        if (height > 0 && window.webkit && window.webkit.messageHandlers.srBridge) {
            window.webkit.messageHandlers.srBridge.postMessage({
                type: "height",
                height: height
            });
        }
    }
    new ResizeObserver(postHeight).observe(heightRoot());
    postHeight();
})();
"""
```

Inject it at document end in `makeUIView` (alongside the message handler):

```swift
configuration.userContentController.addUserScript(
    WKUserScript(
        source: Self.installHeightObserverJS,
        injectionTime: .atDocumentEnd,
        forMainFrameOnly: true
    )
)
```

> **Note**
>
> `.atDocumentEnd` runs after the DOM is available so `querySelector` can find the height root. `forMainFrameOnly: true` avoids installing the observer in iframes.

Posted payloads look like:

```json
{ "type": "height", "height": 420 }
```

### Step 4: Implement Swift → JS via SrJavaScriptBridge

To call `SIR(...)` from Swift without rebuilding HTML, wrap `WKWebView.evaluateJavaScript` in a small bridge and hand it to the consumer once the web view exists.

```swift
final class SrJavaScriptBridge {
    weak var webView: WKWebView?

    func evaluate(_ javaScript: String, completion: ((Any?, Error?) -> Void)? = nil) {
        DispatchQueue.main.async {
            self.webView?.evaluateJavaScript(javaScript, completionHandler: completion)
        }
    }
}
```

Wire it into the host:

1. Keep a `SrJavaScriptBridge` on the coordinator
2. Set `bridge.webView = webView` in `makeUIView`
3. Expose `onBridgeReady: ((SrJavaScriptBridge) -> Void)?` and call it on the next main-queue turn (mutations during `makeUIView` are often dropped, so deferring lets `@State` assignment work)

```swift
var onBridgeReady: ((SrJavaScriptBridge) -> Void)?

// In Coordinator:
let bridge = SrJavaScriptBridge()

// In makeUIView, after creating the web view:
context.coordinator.bridge.webView = webView
let bridge = context.coordinator.bridge
DispatchQueue.main.async {
    onBridgeReady?(bridge)
}
```

> **Tip**
>
> After this step, the host can evaluate JavaScript. [Step 8](#step-8-call-sir-from-swift-optional) shows how to call `SIR(...)` from your app.

### Finished host surface

When Steps 1–4 are combined, the surface looks like:

```swift
init(
    html: String,
    disableScroll: Bool = false,
    onMessage: ((Any) -> Void)? = nil,
    onBridgeReady: ((SrJavaScriptBridge) -> Void)? = nil
)
```

| Feature                | Behavior                                                                                                                 |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `html`                 | Full HTML via `loadHTMLString`; reloads only when the string changes                                                     |
| `disableScroll`        | Disables web-view scroll and bounce                                                                                      |
| `onMessage`            | Every `srBridge` payload (height + widget callbacks)                                                                     |
| `onBridgeReady`        | Fired once after web view creation; provides `SrJavaScriptBridge`                                                        |
| Height observer        | Injected script observes `[data-sr-height-root]` (fallback `body`) and posts `{ type: "height", height }` via `srBridge` |
| Base URL               | `https://widgets.sir.sportradar.com/`                                                                                    |
| Transparent background | Clear web view / scroll view so SwiftUI shows through                                                                    |

### Full host reference {#full-host-reference}

**### Complete SportradarWidgetView implementation**

Reference implementation of the finished host after Steps 1–4. Use it to check your own recreation:

```swift
import SwiftUI
import WebKit

/// Evaluates JavaScript in the widget web view (Swift → JS).
final class SrJavaScriptBridge {
    weak var webView: WKWebView?

    func evaluate(_ javaScript: String, completion: ((Any?, Error?) -> Void)? = nil) {
        DispatchQueue.main.async {
            self.webView?.evaluateJavaScript(javaScript, completionHandler: completion)
        }
    }
}

struct SportradarWidgetView: UIViewRepresentable {
    /// Handler name exposed to JS as `webkit.messageHandlers.srBridge`.
    static let messageHandlerName = "srBridge"

    /// Observes `[data-sr-height-root]` (falls back to `body`) and posts `{ type: "height", height }` via `srBridge`.
    private static let installHeightObserverJS = """
    (function() {
        function heightRoot() {
            return document.querySelector("[data-sr-height-root]") || document.body;
        }
        function postHeight() {
            var el = heightRoot();
            var height = Math.ceil(el.getBoundingClientRect().height);
            if (height > 0 && window.webkit && window.webkit.messageHandlers.srBridge) {
                window.webkit.messageHandlers.srBridge.postMessage({
                    type: "height",
                    height: height
                });
            }
        }
        new ResizeObserver(postHeight).observe(heightRoot());
        postHeight();
    })();
    """

    let html: String
    let disableScroll: Bool

    /// Called when JS posts via `webkit.messageHandlers.srBridge.postMessage(...)`.
    var onMessage: ((Any) -> Void)?

    /// Provides a bridge for evaluating JavaScript after the web view is created.
    var onBridgeReady: ((SrJavaScriptBridge) -> Void)?

    private static let baseURL = URL(string: "https://widgets.sir.sportradar.com/")!

    init(
        html: String,
        disableScroll: Bool = false,
        onMessage: ((Any) -> Void)? = nil,
        onBridgeReady: ((SrJavaScriptBridge) -> Void)? = nil
    ) {
        self.html = html
        self.disableScroll = disableScroll
        self.onMessage = onMessage
        self.onBridgeReady = onBridgeReady
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(onMessage: onMessage)
    }

    func makeUIView(context: Context) -> WKWebView {
        let configuration = WKWebViewConfiguration()
        // JS → Swift: window.webkit.messageHandlers.srBridge.postMessage(payload)
        configuration.userContentController.add(
            context.coordinator,
            name: Self.messageHandlerName
        )
        configuration.userContentController.addUserScript(
            WKUserScript(
                source: Self.installHeightObserverJS,
                injectionTime: .atDocumentEnd,
                forMainFrameOnly: true
            )
        )

        let webView = WKWebView(frame: .zero, configuration: configuration)
        webView.isOpaque = false
        webView.backgroundColor = .clear
        webView.scrollView.backgroundColor = .clear
        webView.scrollView.isScrollEnabled = !disableScroll
        webView.scrollView.bounces = !disableScroll

        context.coordinator.bridge.webView = webView
        // Defer so consumers can safely assign @State (mutations during makeUIView are often dropped).
        let bridge = context.coordinator.bridge
        DispatchQueue.main.async {
            onBridgeReady?(bridge)
        }

        context.coordinator.load(html, into: webView)
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        context.coordinator.onMessage = onMessage
        context.coordinator.load(html, into: webView)
    }

    static func dismantleUIView(_ uiView: WKWebView, coordinator: Coordinator) {
        uiView.configuration.userContentController
            .removeScriptMessageHandler(forName: messageHandlerName)
    }

    final class Coordinator: NSObject, WKScriptMessageHandler {
        let bridge = SrJavaScriptBridge()
        var onMessage: ((Any) -> Void)?
        private var loadedHTML: String?

        init(onMessage: ((Any) -> Void)?) {
            self.onMessage = onMessage
        }

        func load(_ html: String, into webView: WKWebView) {
            guard html != loadedHTML else { return }
            loadedHTML = html
            webView.loadHTMLString(html, baseURL: SportradarWidgetView.baseURL)
        }

        func userContentController(
            _ userContentController: WKUserContentController,
            didReceive message: WKScriptMessage
        ) {
            guard message.name == SportradarWidgetView.messageHandlerName else { return }
            onMessage?(message.body)
        }
    }
}
```

## Using SportradarWidgetView {#using-sportradarwidgetview}

With the host in place, build widget HTML and wire it into your SwiftUI UI.

### Step 5: Build the widget HTML from the JS docs

Use Sportradar’s web widget documentation for:

- the `widgetloader` bootstrap for your client ID
- `SIR("addWidget", selector, widgetName, props)`
- any loader options and callbacks the widget requires

See [Getting Started](https://docs.sportradar.com/resources/widgets/docs/tutorials/getting-started.md) and the [SIR API](https://docs.sportradar.com/resources/widgets/docs/tutorials/SIR.md) for the authoritative JavaScript patterns.

A minimal page shape:

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        html, body { margin: 0; padding: 0; }
    </style>
</head>
<body>
    <div id="sr-widget" data-sr-height-root></div>
    <script type="text/javascript">
        // Loader bootstrap + SIR("addWidget", ...) from Sportradar JS docs
    </script>
</body>
</html>
```

**Notes for iOS hosting:**

- Put `data-sr-height-root` on the element that should drive native auto-height (usually the mount div). Its height is reported (and updated) via `onMessage`. If omitted, height falls back to `document.body`.
- Keep page backgrounds transparent if you want the SwiftUI background to show through.
- Replace the example client ID with your assigned client ID in production.
- Keep the page markup minimal. The native host injects the shared height observer instead of making each widget page responsible for that logic.

> **Warning**
>
> Replace `YOUR_CLIENT_ID` in the widgetloader URL with your actual Client ID before shipping.

### Step 6: Host the page in your SwiftUI UI {#step-6-host-the-page-in-your-swiftui-ui}

Pass the HTML into the finished `SportradarWidgetView`, size from reported height, and optionally keep the JS bridge:

```swift
@State private var widgetHeight: CGFloat = 1
@State private var jsBridge: SrJavaScriptBridge?

SportradarWidgetView(
    html: myWidgetHTML,
    disableScroll: true,
    onMessage: { message in
        if let height = contentHeight(from: message) {
            widgetHeight = height
        } else {
            // Handle widget callbacks posted to srBridge
        }
    },
    onBridgeReady: { bridge in
        jsBridge = bridge
    }
)
.frame(height: widgetHeight)
```

Use `disableScroll: true` when the widget sits inside a native scroll container (`NavigationStack`, `ScrollView`, `List`).

Parse height updates from `onMessage` and apply `.frame(height:)`:

```swift
private func contentHeight(from message: Any) -> CGFloat? {
    guard
        let dict = message as? [String: Any],
        dict["type"] as? String == "height",
        let number = dict["height"] as? NSNumber
    else { return nil }
    let height = CGFloat(truncating: number)
    return height > 0 ? height : nil
}
```

> **Tip**
>
> If you want a fallback until the widget reports its real size, start from a small default or a minimum native height and replace it once the first height message arrives.

### Step 7: Bridge widget callbacks to Swift {#step-7-bridge-widget-callbacks-to-swift}

When the JS docs say to attach callbacks such as `onTrack` or `onItemClick`, forward them into native code through the message handler you registered (this guide uses `srBridge`):

```js
onTrack: function(eventName, eventData) {
    if (window.webkit && window.webkit.messageHandlers.srBridge) {
        window.webkit.messageHandlers.srBridge.postMessage({
            type: "onTrack",
            eventName: eventName,
            eventData: eventData
        });
    }
}
```

Payloads must be JSON-serializable. For nested objects, stringify in JS:

```js
onItemClick: function(target, data) {
    if (window.webkit && window.webkit.messageHandlers.srBridge) {
        window.webkit.messageHandlers.srBridge.postMessage({
            type: "onItemClick",
            target: String(target),
            data: JSON.stringify(data)
        });
    }
}
```

Handle those messages in the same `onMessage` closure used for height. Branch on `type`:

```swift
onMessage: { message in
    guard let dict = message as? [String: Any],
          let type = dict["type"] as? String else { return }
    switch type {
    case "onTrack":
        print("onTrack", dict["eventName"] ?? "", dict["eventData"] ?? "")
    case "onItemClick":
        print("onItemClick", dict["target"] ?? "", dict["data"] ?? "")
    default:
        print("srBridge ←", message)
    }
}
```

This pattern stays the same for all widgets:

1. Implement the callback per the Sportradar JS docs
2. `postMessage` to your message handler (for example `srBridge`) with a `type`
3. Branch on `type` (or equivalent) in Swift

Only the callback name and remaining payload fields change per widget.

> **Note**
>
> Learn more about tracking in the [Widget Tracking & Analytics Guide](https://docs.sportradar.com/resources/widgets/docs/tutorials/tracking-guide.md).

### Step 8: Call SIR(...) from Swift (optional) {#step-8-call-sir-from-swift-optional}

Keep the HTML string stable and update via the bridge from `onBridgeReady`:

```swift
jsBridge?.evaluate("""
SIR("updateWidget", "#sr-widget", { matchId: \(matchID) });
""")

jsBridge?.evaluate("SIR(\"setClientTheme\", \"sportradardark\");")
// SIR("changeLanguage", "de")
```

> **Warning**
>
> Wait for `onBridgeReady` before evaluating. Prefer these API calls over regenerating the HTML string (which reloads the loader and is slower).

## Example of a widget swap

Swapping widgets should not require changing `SportradarWidgetView`. Change only the HTML you pass in (and how you interpret `onMessage`).

**LMT Plus**

```js
SIR("addWidget", "#sr-widget", "match.lmtPlus", {
    matchId: 61591316,
    layout: "single",
    onTrack: function(eventName, eventData) {
        /* post to srBridge */
    }
});
```

**Bet Insights**

```js
SIR("addWidget", "#sr-widget", "betInsights", {
    matchId: 68687766,
    integration: "inline",
    onItemClick: function(target, data) {
        /* post to srBridge */
    }
});
```

The SwiftUI host, height observer, and bridge remain the same.

## Key takeaways

### Keep the host generic

`SportradarWidgetView`, `srBridge`, height reporting, and the base URL stay shared across every widget.

### Isolate widget differences

Widget name, props, loader options, and callbacks live in the HTML / props layer only.

### Size from reported height

Use `disableScroll: true` and `.frame(height:)` from `srBridge` height messages inside native scroll containers.

### Prefer SIR updates over reload

Call `SIR(...)` through `SrJavaScriptBridge` instead of regenerating HTML for live updates.

## Further reading

### Sportradar widget documentation

- [Getting Started](https://docs.sportradar.com/resources/widgets/docs/tutorials/getting-started.md) — loader bootstrap and `addWidget`
- [Global SIR API](https://docs.sportradar.com/resources/widgets/docs/tutorials/SIR.md) — `updateWidget`, themes, language, and other methods
- [Widget Tracking & Analytics Guide](https://docs.sportradar.com/resources/widgets/docs/tutorials/tracking-guide.md) — `onTrack` and analytics patterns
- [Integration Best Practices](https://docs.sportradar.com/resources/widgets/docs/tutorials/integration-best-practices.md) — production hardening
- [FAQ](https://docs.sportradar.com/resources/widgets/docs/tutorials/faq.md) — Client ID, widget names, and entity IDs

### Apple platform references

- [WKWebView](https://developer.apple.com/documentation/webkit/wkwebview) — hosting web content in native apps
- [WKScriptMessageHandler](https://developer.apple.com/documentation/webkit/wkscriptmessagehandler) — JS → native messaging
- [UIViewRepresentable](https://developer.apple.com/documentation/swiftui/uiviewrepresentable) — embedding UIKit views in SwiftUI
