# iOS and Android WebViews (/vela-pro/customization/mobile/native-apps)



Vela Pro runs in standard web engines and does not include a native iOS or Android SDK or wrapper view. To embed Vela Pro in a mobile app, load a web host page inside `WKWebView` on iOS or `android.webkit.WebView` on Android and exchange messages between native code and the workspace over a JavaScript bridge.

Vela Pro and Vela's open-source core have no WebView-specific code paths. Library behavior documented on this page comes directly from the SDK, while platform setup reflects standard iOS and Android WebView practices. Verify platform APIs against Apple and Android documentation for the OS versions your app targets.

## HTML host page [#html-host-page]

Load a standard HTML page whose chart container fills the WebView bounds:

```html
<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
        <style>
            html, body { height: 100%; margin: 0; }
            #chart { height: 100%; }
        </style>
    </head>
    <body>
        <div id="chart"></div>
        <script type="module" src="/chart.js"></script>
    </body>
</html>
```

* **Viewport width**: Keep `width=device-width` in the viewport meta tag. Without it, mobile WebViews can lay out the document at a desktop viewport width, causing `layoutMode: 'auto'` to select the desktop layout. On dedicated phone screens, you can also pin `layoutMode: 'mobile'` (see [Responsive layout](/vela-pro/customization/mobile/responsive)).
* **Safe-area insets**: Include `viewport-fit=cover` when extending the WebView behind a device notch or home indicator, and pad custom page chrome with `env(safe-area-inset-*)`. The workspace's mobile bottom bar, trading sheet, and bar replay prompt apply `env(safe-area-inset-bottom)` automatically.
* **HTTPS or custom-scheme origin**: Serve the page over HTTPS from your web origin, or bundle the built assets inside the app behind a dedicated scheme or asset handler (`WKURLSchemeHandler` on iOS, `WebViewAssetLoader` on Android). Avoid `file://` URLs because browser origin rules block ES module scripts, `fetch`, and Vela Pro's dynamic `import()` chunks on `file://` pages.
* **CORS configuration**: Network requests made from a bundled custom-scheme or asset-loader origin to your market data backend are cross-origin, so your API servers must return `Access-Control-Allow-Origin` headers permitting that origin.

See [Installation](/vela-pro/get-started/setup) for bundling `@luxalgo/vela-pro` and the core in your web build.

## WebView configuration [#webview-configuration]

| Capability          | Purpose                                         | iOS (`WKWebView`)  | Android (`WebView`)                                       |
| ------------------- | ----------------------------------------------- | ------------------ | --------------------------------------------------------- |
| JavaScript          | All workspace and chart execution               | Enabled by default | Disabled by default (`settings.javaScriptEnabled = true`) |
| DOM storage         | Default `localStorage` state persistence        | Enabled by default | Disabled by default (`settings.domStorageEnabled = true`) |
| WebGL2 or 2D Canvas | Chart rendering                                 | Enabled by default | Enabled by default                                        |
| Web Workers         | Pine Script® engine and code editor             | Enabled by default | Enabled by default                                        |
| Network             | Data provider HTTP requests and WebSocket feeds | HTTPS and WSS      | HTTPS, WSS, and `android.permission.INTERNET`             |

Use HTTPS for REST endpoints and WSS for streaming connections. Both iOS App Transport Security and modern Android target SDK levels block cleartext HTTP and WS traffic by default.

### Rendering and Pine Script® workers [#rendering-and-pine-script-workers]

The chart renderer requires no platform flags. Its `nativeBackend` option defaults to `'auto'`, selecting WebGL2 when supported by the WebView and falling back to 2D Canvas otherwise. Passing `nativeBackend: 'canvas2d'` forces 2D Canvas rendering, which supports every feature except candle `glow` (WebGL2 only).

By default, each chart executes Pine Script® indicators inside a Web Worker spawned from a `blob:` URL. If your host page enforces a Content Security Policy without `worker-src blob:` or runs in an environment that blocks Blob workers, switch the engine to main-thread execution:

```ts
import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro({ pineEngine: { engine: 'inprocess' } });
```

In-process execution runs indicator calculations on the UI thread, so compute-heavy scripts can delay frame rendering while evaluating. The Pine code editor also spawns a dedicated `blob:` worker for language intelligence; pass `codeEditor: false` to disable the code editor in mobile views where script editing is not exposed.

### Storage isolation [#storage-isolation]

When `persist: true` is enabled, `VelaWorkspace` saves its state document to `localStorage`. Vela Pro's built-in stores (watchlists, alerts, per-symbol drawings, indicator templates, favorite indicators, journal entries, and editor drafts) also default to `localStorage`.

Inside a native app, `localStorage` belongs exclusively to that WebView container. It is isolated from Safari and Chrome, does not sync across the user's devices, and is cleared when the user resets app storage, uninstalls the app, or when the OS reclaims WebView data. Do not rely on WebView `localStorage` for durable user data. Configure custom storage adapters backed by your server (see [Server-side storage](/vela-pro/persistence/backend)), or forward state snapshots to native storage across the JavaScript bridge below.

## JavaScript bridge [#javascript-bridge]

Native code calls into the workspace by evaluating JavaScript in the WebView. Web code sends events to native code through the platform's script message interface (`window.webkit.messageHandlers.<name>.postMessage(...)` on iOS and a `@JavascriptInterface` object on Android). The module below sets up both directions and types the platform globals:

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { enableVelaPro } from '@luxalgo/vela-pro';

type NativePort = { postMessage(json: string): void };
declare global {
    interface Window {
        webkit?: { messageHandlers?: { chart?: NativePort } }; // iOS WKScriptMessageHandler named "chart"
        AndroidChart?: NativePort; // Android @JavascriptInterface named "AndroidChart"
        chartBridge?: typeof bridge;
    }
}

function post(message: Record<string, unknown>): void {
    const port = window.webkit?.messageHandlers?.chart ?? window.AndroidChart;
    port?.postMessage(JSON.stringify(message));
}

enableVelaPro();
const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    timeframe: '60',
    live: true,
    providers: { binance: () => new BinanceProvider() },
});

// Native-to-web entry points called via evaluateJavaScript / evaluateJavascript
const bridge = {
    setSymbol: (symbol: string) => workspace.active.setSymbol(symbol),
    setTimeframe: (timeframe: string) => workspace.active.setTimeframe(timeframe),
    setTheme: (theme: 'dark' | 'light') => workspace.setTheme(theme),
    applyState: (json: string) => workspace.applyState(JSON.parse(json)),
};
window.chartBridge = bridge;

// Web-to-native events serialized as JSON strings
workspace.on('state:changed', () => post({ type: 'state', state: workspace.getState() }));
workspace.chart.on('market:changed', ({ symbol, timeframe }) => post({ type: 'market', symbol, timeframe }));
post({ type: 'ready' });
```

| Message `type` | Emitted when                                                              | Payload fields                               |
| -------------- | ------------------------------------------------------------------------- | -------------------------------------------- |
| `ready`        | The workspace and `window.chartBridge` are initialized                    | None                                         |
| `state`        | `state:changed` fires (\~500ms after a persistable workspace change)      | `state` document from `workspace.getState()` |
| `market`       | `market:changed` fires after a symbol or timeframe switch paints new bars | `symbol` and `timeframe`                     |

Notice that `persist` is omitted in this configuration. Instead, the native host persists the latest `state` payload and calls `chartBridge.applyState(json)` after receiving `ready` on subsequent launches. `applyState` ignores invalid or outdated fields so schema changes do not break startup. See [Events and subscriptions](/vela-pro/charts/events) for additional workspace and chart methods you can expose on the bridge.

### iOS [#ios]

Register a `WKScriptMessageHandler` named `"chart"` on `WKUserContentController` before loading the page. Each `post()` call invokes `userContentController(_:didReceive:)` with the JSON string in `message.body`:

```text
let controller = WKUserContentController()
controller.add(handler, name: "chart")          // handler implements WKScriptMessageHandler
let configuration = WKWebViewConfiguration()
configuration.userContentController = controller
let webView = WKWebView(frame: .zero, configuration: configuration)

// Native to web:
webView.evaluateJavaScript("chartBridge.setSymbol(\"ETHUSDT\")")
```

### Android [#android]

Register an object annotated with `@JavascriptInterface` under `"AndroidChart"` before loading the URL. Only annotated methods are visible to JavaScript. Those callbacks receive strings or primitives and run on a background thread rather than the main UI thread:

```text
class ChartPort(private val onMessage: (String) -> Unit) {
    @JavascriptInterface
    fun postMessage(json: String) = onMessage(json)
}

webView.settings.javaScriptEnabled = true
webView.settings.domStorageEnabled = true
webView.addJavascriptInterface(ChartPort { json -> /* parse JSON and dispatch to main thread */ }, "AndroidChart")
webView.loadUrl("https://app.example.com/chart")

// Native to web (must be called on the main thread):
webView.evaluateJavascript("chartBridge.setSymbol(\"ETHUSDT\")", null)
```

Android also supports `WebMessagePort` and `WebViewCompat.addWebMessageListener` as alternatives to `addJavascriptInterface` while keeping the same JSON message format on the web side.

<Warning>
  Registered message handlers and JavaScript interfaces are accessible to every document loaded in that WebView. Restrict WebView navigation to your own trusted origin. When building JavaScript call strings in native code, encode arguments with a JSON serializer instead of string concatenation so quotes or special characters in symbols and state payloads cannot corrupt the expression.
</Warning>

## Debugging [#debugging]

* **iOS**: Turn on **Web Inspector** in **Settings**, **Safari**, **Advanced** on the iOS device, set `webView.isInspectable = true` in debug builds (required on iOS 16.4+), connect the device to a Mac, and select the WebView from Safari's **Develop** menu.
* **Android**: Call `WebView.setWebContentsDebuggingEnabled(true)` in debug builds, enable USB debugging on the device, and inspect the WebView at `chrome://inspect` in desktop Chrome.

In the DevTools console, evaluate `document.querySelector('[data-layout]')?.dataset.layout` to check whether the workspace resolved to `'mobile'` or `'desktop'`. Console errors mentioning `Worker` or `Content Security Policy` indicate that `blob:` workers are blocked and require either `worker-src blob:` in your CSP or `pineEngine: { engine: 'inprocess' }`.

<Note>
  LuxAlgo does not publish sample iOS or Android host apps for Vela Pro. Your application team owns the native WebView wrapper, bridge integration, and verification across your target devices and OS versions.
</Note>

## Related [#related]

* [Responsive layout](/vela-pro/customization/mobile/responsive)
* [Server-side storage](/vela-pro/persistence/backend)
* [Events and subscriptions](/vela-pro/charts/events)
* [Production checklist](/vela-pro/reference/production)
