Install in your app

The mini-app needs a WebView with a handful of settings turned on, a message bridge injected at document start, and the ?embed=1 flag on every URL you open. This page shows the minimal setup for Android, iOS and a web iframe.

WebView requirements

RequirementWhy
JavaScript enabledThe whole mini-app is client rendered after the first HTML.
DOM storage (sessionStorage)The sign-in token and the embed flag live in sessionStorage for the tab. Without it the viewer is signed out on every navigation.
Media playback without user gestureThe player autoplays when it opens; otherwise the viewer sees a black screen until they tap.
Inline media playbackThe player draws its own controls over the video; a system fullscreen player would hide them.
Protected media permissionWidevine / FairPlay licences are refused unless the host grants it. See DRM in WebViews.
Follow redirects and POSTSign-in is a POST followed by 303 redirects, one of which may go to the TrueID binding page on another domain.
?embed=1A native WebView is the top frame, so the mini-app cannot detect it is embedded. The flag turns on the message bridge and the full-bleed layout.

Android (WebView)

  1. Add the AndroidX WebKit library so you can inject the bridge before the page runs.
  2. Configure the WebView settings and the protected-media permission.
  3. Register a message listener and inject the glue script at document start.
  4. Open the page you want with postUrl and your token, so the viewer arrives signed in.
build.gradleGradle
implementation("androidx.webkit:webkit:1.12.1")
TrueVisionsWebView.ktKotlin
val webView = WebView(context)
with(webView.settings) {
    javaScriptEnabled = true
    domStorageEnabled = true
    mediaPlaybackRequiresUserGesture = false
    // Optional: lets TrueVisions recognise your app in logs.
    userAgentString = "$userAgentString TrueApp/${BuildConfig.VERSION_NAME}"
}

webView.webChromeClient = object : WebChromeClient() {
    // Required for Widevine: grant PROTECTED_MEDIA_ID to the mini-app origin.
    override fun onPermissionRequest(request: PermissionRequest) {
        val allowed = request.resources.filter {
            it == PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID
        }
        if (allowed.isNotEmpty() && request.origin.host == "mini-app.truevisions.co.th") {
            request.grant(allowed.toTypedArray())
        } else {
            request.deny()
        }
    }
}

// The mini-app posts to window.parent, which is the page itself inside a
// WebView. Forward those events to Kotlin.
val origins = setOf("https://mini-app.truevisions.co.th")
if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
    WebViewCompat.addWebMessageListener(webView, "truevisionHost", origins) { _, message, _, _, _ ->
        onMiniAppMessage(JSONObject(message.data ?: return@addWebMessageListener))
    }
}
if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
    WebViewCompat.addDocumentStartJavaScript(
        webView,
        """
        window.addEventListener('message', function (e) {
          if (e.data && e.data.channel === 'truevision-app') {
            truevisionHost.postMessage(JSON.stringify(e.data));
          }
        });
        """.trimIndent(),
        origins,
    )
}

// Open a page signed in: POST your token to the page itself.
val body = "partner_token=" + URLEncoder.encode(accessToken, "UTF-8") +
    "&device_id=" + URLEncoder.encode(deviceId, "UTF-8") +
    "&session_id=" + URLEncoder.encode(sessionId, "UTF-8") +
    "&platform=ANDROID&version=" + BuildConfig.VERSION_NAME +
    "&device_model=" + URLEncoder.encode(Build.MODEL, "UTF-8")
webView.postUrl("https://mini-app.truevisions.co.th/th/trueapp/sport?embed=1", body.toByteArray())

// Opened without a token (plain loadUrl), the page sends the viewer to
// TrueID sign-in first; there is no guest mode.
Sending a command to the mini-appKotlin
webView.evaluateJavascript(
    "window.postMessage({channel:'truevision-app',type:'pause'}, '*')", null
)

iOS (WKWebView)

  1. Create a WKWebViewConfiguration with inline playback and no user-action requirement for media.
  2. Add a user script at document start that forwards bridge messages to a WKScriptMessageHandler.
  3. Load a POST URLRequest with your token for the page you want.
TrueVisionsWebView.swiftSwift
let config = WKWebViewConfiguration()
config.allowsInlineMediaPlayback = true
config.mediaTypesRequiringUserActionForPlayback = []
config.websiteDataStore = .default()   // keeps sessionStorage for the lifetime of the view

let bridge = """
window.addEventListener('message', function (e) {
  if (e.data && e.data.channel === 'truevision-app') {
    window.webkit.messageHandlers.truevision.postMessage(e.data);
  }
});
"""
config.userContentController.addUserScript(
    WKUserScript(source: bridge, injectionTime: .atDocumentStart, forMainFrameOnly: true)
)
config.userContentController.add(self, name: "truevision")   // self: WKScriptMessageHandler

let webView = WKWebView(frame: .zero, configuration: config)
webView.customUserAgent = (webView.value(forKey: "userAgent") as? String ?? "") + " TrueApp/\(appVersion)"

// Open a page signed in: POST your token to the page itself.
var request = URLRequest(url: URL(string: "https://mini-app.truevisions.co.th/th/trueapp/sport?embed=1")!)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
var form = URLComponents()
form.queryItems = [
    .init(name: "partner_token", value: accessToken),
    .init(name: "device_id", value: deviceId),
    .init(name: "session_id", value: sessionId),
    .init(name: "platform", value: "iOS"),
    .init(name: "version", value: appVersion),
    .init(name: "device_model", value: UIDevice.current.model),
]
request.httpBody = form.percentEncodedQuery?.data(using: .utf8)
webView.load(request)

// WKScriptMessageHandler
func userContentController(_ c: WKUserContentController, didReceive message: WKScriptMessage) {
    guard let body = message.body as? [String: Any], body["channel"] as? String == "truevision-app" else { return }
    handleMiniAppMessage(body)
}

// Sending a command to the mini-app.
webView.evaluateJavaScript("window.postMessage({channel:'truevision-app',type:'pause'}, '*')")

Rotate for the player

When the player opens, the mini-app sends orientation with "landscape". When the player closes, it sends "portrait". Rotate your screen when you get these messages.

Android: handle orientationKotlin
fun onMiniAppMessage(msg: JSONObject) {
    if (msg.optString("type") == "orientation") {
        activity.requestedOrientation =
            if (msg.optString("orientation") == "landscape")
                ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
            else
                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT   // or the value you had before
    }
}

On Android the player also asks for fullscreen on the first tap. A WebView only allows this if your WebChromeClient implements onShowCustomView and onHideCustomView. Without them, the request fails and nothing else changes.

iOS: handle orientationSwift
// In the view controller that shows the WebView.
var playerLandscape = false

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    playerLandscape ? .landscape : .portrait
}

func handleOrientation(_ value: String) {
    playerLandscape = (value == "landscape")
    if #available(iOS 16.0, *) {
        setNeedsUpdateOfSupportedInterfaceOrientations()
        view.window?.windowScene?.requestGeometryUpdate(
            .iOS(interfaceOrientations: playerLandscape ? .landscape : .portrait)
        )
    } else {
        UIViewController.attemptRotationToDeviceOrientation()
    }
}

requestGeometryUpdate needs iOS 16 or later. On older iOS, attemptRotationToDeviceOrientation only rotates when the viewer turns the phone. Your app must list the landscape orientations in Info.plist (UISupportedInterfaceOrientations), or iOS will not rotate.

Web (iframe)

On the web the mini-app detects the iframe itself, so ?embed=1 is optional. Messages arrive on the parent window via the standard message event. Grant the iframe the features the player needs.

index.htmlHTML
<iframe
  src="https://mini-app.truevisions.co.th/en/trueapp/sport"
  allow="autoplay; encrypted-media; fullscreen; picture-in-picture"
  style="border:0;width:100%;height:100%"
></iframe>

<script>
  const frame = document.querySelector("iframe");
  window.addEventListener("message", (e) => {
    if (e.origin !== "https://mini-app.truevisions.co.th") return;
    if (e.data?.channel !== "truevision-app") return;
    console.log("mini-app:", e.data);
  });
  // Command: pause.
  frame.contentWindow.postMessage({ channel: "truevision-app", type: "pause" }, "https://mini-app.truevisions.co.th");
</script>

Signing in from an iframe requires a top-level POST (a form whose target is the iframe name works). The token is handed to the frame in a URL fragment and never leaves it.

Go-live checklist

  • Your partner slug and the production origin have been confirmed by TrueVisions.
  • Both origins (mini-app and *.trueid.net binding page) are reachable from the WebView, including any allow-list your app enforces.
  • The protected-media permission is granted on Android and the DRM check passes on your test devices.
  • orientation messages rotate or lock the WebView (see Rotate for the player); close dismisses it.
  • subscribe with opened: false opens purchaseUrl (the TrueVisions offer page); open-app opens the TrueVisions NOW app.