Browser & WebView

Web pages inside the app, from the browser plugin. Browser.open(url) shows a page in the system browser sheet (or, with embedded: true, in a screen of its own: a close bar over a UIWebViewNode) and resolves with the return URL it reached; UIWebViewNode(props) is a web page as a box of a screen's layout, and WebView(params) a web page full screen, with your controls over it. openURL hands a URL to the system instead — the external browser, and tel:, sms:, mailto: to the dialer, messages, mail; a page shown INSIDE the app — a sheet, an OAuth sign-in, a checkout — is Browser.open.

  • open a web page inside the app without leaving it
  • sign in through an OAuth provider's page and come back to the app
  • run a hosted checkout and learn whether it was paid
  • show a web page as part of a screen
  • show a web page full screen with your own buttons over it
  • send messages between the app and the page's JavaScript
  • know when the page has loaded or failed to load

Platforms: iOS, Android, the web and the web player (a popup and an iframe there, which see little of a page of another origin); not on desktop — use openURL there; in the le.codes viewer app a return URL comes back in the sheet only on iOS with a custom scheme, so use embedded: true there — check Browser.supported / WebView.supported. The page inside a screen (UIWebViewNode, and so embedded: true): iOS, Android and the web (Web Lite, an iframe); not in the web player — check UIWebViewNode.supported.

At a glance

TypeScript
const status = UIText("").style({ fontSize: 14 })

const help = UIButton(UIText("Help center")).onClick(() => {
  Browser.open("https://example.com/help")                     // the system browser sheet, over the app
    .then(() => { status.text = "Back in the app" })            // resolves when the user closes it
    .catch(e => { status.text = `Couldn't open it: ${e.message}` })
})

const page = UIWebViewNode.supported
  ? UIWebViewNode({ url: "https://example.com" }).style({ height: 320 })   // a page inside the screen
  : UIText("No web view on this device")

UIScreen(help, status, page).style({ pt: "safe-top", p: 16, gap: 12 }).open()

Add the plugin: app.json plugins

Browser, UIWebViewNode and WebView need the browser plugin, listed in the app's app.json — write it there, or let lecodes app plugin add browser write it into an app.json the project already has:

JSON
{ "plugins": { "browser": "*" } }

The list is an object (id → version), one for every platform: it becomes the bundle's // plugins: header, and a plugin it does not name is not there — in a shell built from the project, in Web Lite and in the web player alike; the compile warns about one the app uses and does not list. The le.codes viewer app has the plugin whatever the list says. A shell app that gets a sign-in or a checkout back through the sheet also sets its URL scheme, "urlScheme": "myshop" (Where the return URL comes back).

Open a web page inside the app: Browser.open

TypeScript
Browser.supported: boolean                 // this host has the system sheet
Browser.open(url: string, options?: {
  returnUrl?: string | string[]              // URL prefixes that end the page: open resolves with the one reached
  embedded?: boolean                         // a screen of a close bar over a UIWebViewNode instead of the sheet
  ephemeral?: boolean                        // a private session: no cookies shared with the browser
  color?: string                             // the sheet's bar, "#RRGGBB"
  title?: string                             // embedded: the bar's title until the page reports its own
}): Promise<string | null>                   // the return URL reached, or null when the user left

To show a page without leaving the app, open it in the system's in-app browser sheet: SFSafariViewController on iOS, a Chrome Custom Tab on Android, a popup window on the web. It comes over the app with the browser's saved logins, passkeys and Apple Pay; the app sees nothing of the page, and open resolves when the user closes it (null without a returnUrl).

  • url must be http(s): anything else rejects with invalid — and on the web so does a popup the browser blocked, so call open from a tap.
  • One sheet at a time: a second open while one is up rejects with busy.
  • On the web, reaching a page of the app's own origin ends the popup at once, and open resolves with that URL: show a page of the app's own site in a WebView there (or embedded: true).
  • color tints the sheet's bar on Android and on iOS (not the iOS sign-in sheet of a custom-scheme returnUrl); the web ignores it.
  • A PDF opens the same way: the sheet shows it on iOS and in a browser with a PDF viewer; on Android it is up to the browser behind the Custom Tab, and Android's web view (embedded, UIWebViewNode, WebView) does not render PDFs.
TypeScript
const openPage = (url: string) => {
  if (!Browser.supported) { openURL(url); return }           // desktop: the system browser instead
  Browser.open(url, { color: "#1E88E5" })                       // the sheet's bar in your color
    .catch(e => toast(`Couldn't open the page: ${e.message}`))
}

UIScreen(
  UIButton(UIText("Terms of service")).onClick(() => openPage("https://example.com/terms")),
).style({ pt: "safe-top", p: 16 }).open()

Sign in with an OAuth provider and come back: returnUrl

To sign someone in on an OAuth provider's login page (Google, GitHub, a company's single sign-on) and come back to the app, open the page in the in-app browser sheet — the surface providers accept, with the browser's saved logins — and pass the redirect URL you registered with the provider as returnUrl. When the provider redirects there, the sheet closes and open resolves with that URL; the code is in its query.

TypeScript
import { signInWithCode } from "./auth.server"                  // your server: code → token → db.auth.signIn

const RETURN = "myshop://oauth"                                  // app.json "urlScheme": "myshop"
const authUrl = "https://auth.example.com/authorize?response_type=code&client_id=YOUR_CLIENT_ID" +
  "&redirect_uri=" + encodeURIComponent(RETURN)

const signIn = async () => {
  const back = await Browser.open(authUrl, { returnUrl: RETURN })   // "myshop://oauth?code=…", or null
  const code = back && /[?&]code=([^&#]+)/.exec(back)?.[1]
  if (!code) return toast("Sign-in cancelled")
  await signInWithCode(decodeURIComponent(code))
  toast("Signed in")
}

UIScreen(UIButton(UIText("Sign in")).onClick(() => { signIn() }))
  .style({ pt: "safe-top", p: 16 }).open()
  • Use a custom scheme for the return (myshop://oauth) and set it in app.json as "urlScheme": "myshop"; lecodes app sync writes it into the iOS and Android shells. On iOS the sign-in sheet (ASWebAuthenticationSession) catches the redirect itself; on Android the redirect reaches the app as its url event (deep links), which needs the scheme registered; on the web a custom scheme never comes back, so there the redirect must be a page of the app's own origin. The returnUrls of one sheet share one scheme, else open rejects.
  • The code is your server's to redeem: a server function exchanges it with the provider (the client secret stays on the server) and signs the person in with db.auth.signIn(userId) — Sign-in.
  • ephemeral: true asks for a private session that reuses no saved login — honored on iOS only, with a custom-scheme returnUrl.
  • When the person closes the sheet instead, open resolves with null.

Hosted checkout: learn whether it was paid

To take a payment on a payment provider's hosted checkout page and learn how it ended, pass the success and failure URLs the checkout redirects to as returnUrl: open resolves with the one reached, or null when the person closed the page. With embedded: true the page runs in a screen of its own — a close bar over a UIWebViewNode — which catches the return URL itself — https included, with no URL scheme or app links, in the le.codes viewer app too — so on iOS and Android the return page is never loaded.

TypeScript
const PAID = "https://shop.example.com/checkout/paid"           // the URLs your payment provider
const FAILED = "https://shop.example.com/checkout/failed"       // redirects to at the end

const pay = async (checkoutUrl: string) => {
  const back = await Browser.open(checkoutUrl, { returnUrl: [PAID, FAILED], embedded: true, title: "Payment" })
  if (back?.startsWith(PAID)) toast("Paid, thank you")
  else if (back?.startsWith(FAILED)) toast("The payment did not go through")
  else toast("Checkout closed")                                  // null: the user closed it
}

Router.init(UIScreen(
  UIButton(UIText("Pay 9.99")).onClick(() => { pay("https://pay.example.com/session/123") }),
).style({ pt: "safe-top", p: 16 }))
  • The return URL says where the page went, not that the money arrived: confirm the payment on your server (the provider's webhook or API) before you ship the order.
  • The embedded page goes onto the Router when the Router's page is on screen — its close button, the back button and the back swipe end it with null, and so does the page calling window.close() — else it opens in place of the current destination, which comes back after. Its bar follows the app's theme; color is the sheet's.
  • The screen is UIScreen(bar, UIWebViewNode({ url, stops: returnUrls }).style({ flex: 1 })) — build one of your own for other chrome (below). On the web (Web Lite) the node in that screen is the page's iframe; the web player draws no UIWebViewNode, so embedded: true rejects there.
  • On iOS Apple Pay works in the embedded page as long as the page has no bridge and no evaluate, and Browser.open uses neither. Without embedded the checkout runs in the sheet, with the browser's Apple Pay and saved logins; its return then follows the table below.
  • On the web the iframe sees a return only on the app's own origin: there, the return URLs must be addresses of the app itself.

Where the return URL comes back, per platform

Whether open resolves with the return URL depends on the surface, the kind of URL and the host:

the sheet, custom scheme (myshop://…) the sheet, https embedded: true
iOS caught by the sheet itself, no registration only as a verified link of the app any URL
Android the app's url event: needs app.json urlScheme only as a verified link of the app any URL
the web (Web Lite) never the first page of the app's own origin the popup reaches a URL of the app's own origin
the web player never the first page of the app's own origin the popup reaches no host node: open rejects
le.codes viewer app iOS only never any URL
desktop no plugin: use openURL — —
  • urlScheme belongs to a shell app (Custom URL scheme): lecodes app sync writes it into the iOS Info.plist and the Android manifest. Lowercase letters, digits, + - ., starting with a letter, never http or https. The shells register that scheme, not verified https links (universal links, App Links): app.json has no key for those.
  • The le.codes viewer app registers no scheme or link of a project: embedded: true is the way to get a return there (and, on iOS, a custom scheme in the sheet).
  • On the web the popup resolves with the first URL of the app's own origin it lands on, whether or not it matches returnUrl; a custom scheme never comes back.

A web page as part of a screen: UIWebViewNode

TypeScript
UIWebViewNode.supported: boolean             // static — iOS, Android, Web Lite; false in the web player, desktop, headless
UIWebViewNode(props?: {
  url?: string                               // live: a write loads it
  stops?: string[]                           // live: URL prefixes that end a flow — not loaded, `onStop` instead
  externalLinks?: "open" | "block"           // live: tel:, mailto:, intent:, other apps — to the system (default) or dropped
  bridge?: boolean                           // window.lecodes in the page; default false — at creation only
  userAgent?: string                         // at creation only
  ephemeral?: boolean                        // a private session: nothing kept after the node goes — at creation only
}): UIWebViewNode

node.url = "https://example.com/next"        // loads it; writing the same URL again reloads it
node.stops = [PAID, FAILED]                  // the same as setStops
node.externalLinks = "block"

To show a web page between your own elements — terms above an "Accept" button, a page in a card — use a UIWebViewNode: a node of the screen's layout, a box among its children like a UIImage, with the page drawn in it. A page that fills the screen with controls over it stays a WebView pushed as a destination (below); the node has no open, onBack or widgets.

TypeScript
// app.json: "plugins": { "browser": "*" }
const terms = UIWebViewNode({ url: "https://example.com/terms" })
  .style({ flex: 1, borderRadius: 12 })                              // a box of the layout: its styles size it

UIScreen(
  UIText("Terms of service").style({ fontSize: 20, fontWeight: 700 }),
  UIWebViewNode.supported ? terms : UIText("No web view on this device"),
  UIButton(UIText("Accept")).onClick(() => toast("Accepted")),       // between your own elements
).style({ pt: "safe-top", p: 16, gap: 12 }).open()
  • It is placed like any element: give it a height, or flex: 1 in a column, and borderRadius rounds the page (the node clips: overflow: "hidden" is its default). It knows nothing of the safe area: keep it inside the screen's padding.
  • url, stops and externalLinks are live; a getter answers what was written last, not where the page navigated — that is onNavigate. bridge, userAgent and ephemeral make the platform's web view, so they are read once, when the node is first shown: give them to UIWebViewNode(...) (later writes are ignored, with a line in the device's log).
  • Its calls (load, evaluate, …) work from the start, even in the tick the node is built.
  • Its events are methods: onNavigate, onLoad, onError, onStop, onMessage (events); a node has no exit — window.close() in its page does nothing.
Note

on the web (Web Lite) the node is an iframe in its box, the same page as the fullscreen WebView's: of a page of another origin it knows no navigation, no title and no link (onLoad reports the URL asked for; onStop fires for a stop URL of the app's own origin only; externalLinks acts on a same-origin page's links only), userAgent is ignored and ephemeral is the frame's credentialless (Chromium). In the web player, on desktop and in headless tests the node is an empty box of its size and UIWebViewNode.supported is false (building one there warns once) — branch on it as above. A WebView is never a part of a screen: handed to one as a child it is reported and skipped — a page in a screen is a UIWebViewNode.

A web page full screen: Router.push and widgets

To show a web page full screen, push the WebView itself: like a map or a camera preview it is a destination of its own (NativeView) — Router.push(view) shows it, the back button and the back swipe pop it, and your controls float over it as its widgets. A page that is a part of a screen is a UIWebViewNode (above).

TypeScript
const MENU = "https://example.com/menu"
const page = WebView({ url: MENU })

const close = UIWidget(
  UIButton(UIText("Close").style({ color: "white" })).onClick(() => Router.pop()),
).style({ top: "safe-top", right: 16, px: 12, py: 8, borderRadius: 8, bgColor: "rgba(0,0,0,0.6)" })
page.widgets(close)                                               // floats over the page while it is shown

Router.init(UIScreen(
  UIButton(UIText("Open the menu")).onClick(() => {
    if (WebView.supported) Router.push(page)                    // the page is the destination
    else openURL(MENU)                                            // desktop: the system browser
  }),
).style({ pt: "safe-top", p: 16 }))

For a header of yours above the page rather than over it, put a UIWebViewNode in a screen under a bar (flex: 1) — what Browser.open with embedded: true builds — and push that screen.

Talk to the page: bridge, postMessage, evaluate

To send data between the app and the page's JavaScript, create the page with bridge: true: the page gets window.lecodes, whose postMessage(data) fires the message event, and the app's page.postMessage(data) calls the page's window.lecodes.onMessage(data). Data is JSON. evaluate(js) runs a script in the page and resolves with its value, as JSON. A UIWebViewNode and a WebView have the same calls; the events are onMessage(cb) on the node, on("message", cb) on the view.

TypeScript
const page = UIWebViewNode({ url: "https://example.com/widget.html", bridge: true }).style({ flex: 1 })

page.onMessage(({ data }) => {                                  // the page called window.lecodes.postMessage(data)
  if (data === "ready") page.postMessage({ theme: "dark" })      // → window.lecodes.onMessage(data) in the page
  else console.log("from the page:", JSON.stringify(data))
})
page.onLoad(() => {
  page.evaluate("document.title")                               // run JavaScript in the page, get JSON back
    .then(title => console.log("page title:", title))
    .catch(e => console.log("evaluate failed:", e.message))
})

UIScreen(page).style({ pt: "safe-top" }).open()

The page's side (https://example.com/widget.html):

HTML
<script>
  // window.lecodes is there before the page's scripts run on iOS and Android; on the web and in
  // older Android web views it comes later — wait for it
  const withBridge = (f) => window.lecodes ? f(window.lecodes) : setTimeout(() => withBridge(f), 50)
  withBridge((bridge) => {
    bridge.onMessage = (data) => { document.body.dataset.theme = data.theme }
    bridge.postMessage("ready")
  })
</script>
  • The bridge is the main frame's: an iframe inside the page has none.
  • On iOS a bridge turns Apple Pay off in that page, and so does each evaluate until the page's next navigation — keep both off for a checkout page.
  • On the web the bridge, evaluate and postMessage need a page of the app's own origin (the two calls reject with failed otherwise); a page of another origin can still send with parent.postMessage({ lecodes: data }, "*").

Know when the page loaded or failed: events

TypeScript
node.onNavigate(({ url }) => {})             // a main-frame navigation started      — view.on("navigate", …)
node.onLoad(({ url, title }) => {})          // the page finished loading; title "" when it has none
node.onError(({ url, message }) => {})       // the page failed to load
node.onStop(({ url }) => {})                 // a URL of `stops` was reached: not loaded
node.onMessage(({ data }) => {})             // window.lecodes.postMessage(data) — bridge: true
view.on("exit", () => {})                    // a WebView's page called window.close() (a node has none)

To show a loading state, the page's title or an error, listen to the page's events:

TypeScript
const heading = signal("Loading…")
const canGoBack = signal(false)
const page = UIWebViewNode({ url: "https://example.com" }).style({ flex: 1 })

page.onNavigate(() => { heading.value = "Loading…" })                       // a new page started
page.onLoad(({ title, url }) => {                                           // it finished loading
  heading.value = title || url
  page.canGoBack().then(can => { canGoBack.value = can })
})
page.onError(({ message }) => { heading.value = `Couldn't load: ${message}` })

const back = UIButton(UIText("‹ Back"))
  .style({ opacity: () => canGoBack.value ? 1 : 0.3 })
  .onClick(() => { page.goBack() })

UIScreen(UIRow(back, UIText(() => heading.value).style({ flex: 1 })).style({ gap: 8, p: 8 }), page)
  .style({ pt: "safe-top" }).open()
  • stops (or setStops) end a flow without loading its last page: a navigation to a URL that starts with one — a link, a redirect, a form post — is cancelled and reported as stop. That is how the embedded Browser.open catches its returnUrl.
  • On the web the iframe sees less: navigate comes for the app's own loads only, error and exit never fire, and a page of another origin reports only load, with the URL the app asked for and no title — a stop is caught only in the app's own load or, once the page has loaded, on the app's own origin.

Drive the page: load, goBack, reload, clearData

TypeScript
page.load(url, headers?): Promise<void>        // headers go with the first request; "invalid" for a non-web URL
page.loadHtml(html, baseUrl?): Promise<void>   // relative URLs in it resolve against baseUrl
page.setStops(stops): Promise<void>            // replace the stop list (a node's `stops` too)
page.reload(): Promise<void>
page.stopLoading(): Promise<void>
page.goBack(): Promise<void>
page.goForward(): Promise<void>
page.canGoBack(): Promise<boolean>
page.evaluate(js): Promise<Json>               // rejects "failed"
page.postMessage(data): Promise<void>          // → window.lecodes.onMessage(data)
page.clearData(): Promise<void>                // cookies and storage
WebView.supports(method): boolean              // false on a host whose half is older than the method

To load another page, move through the page's history or clear what it stored, call the page's methods — a UIWebViewNode's and a WebView's are the same; each returns a promise.

  • clearData() and ephemeral reach beyond the page: on Android cookies and web storage belong to the app, shared by all its web views, so both clear them all (ephemeral when the page goes); on iOS clearData() of a page without ephemeral clears the app's shared web data; on the web clearData() does nothing.
  • externalLinks: "open" (the default) hands non-web links — tel:, mailto:, intent:, a bank's app in a checkout — to the system; "block" drops them.
  • A target="_blank" link opens in the same page on iOS and Android: there is no second window.
  • On the web, load headers, userAgent, ephemeral and externalLinks are ignored, and goBack / goForward / stopLoading do nothing on a page of another origin.

Per platform

What the sheet and the web view are on each host:

  • iOS — the sheet is SFSafariViewController, or for a custom-scheme returnUrl an ASWebAuthenticationSession (the system's sign-in sheet); UIWebViewNode and WebView are a WKWebView.
  • Android — the sheet is a Chrome Custom Tab (ephemeral ignored); UIWebViewNode and WebView are the system WebView.
  • The web (Web Lite) — the sheet is a popup window (color and ephemeral ignored); UIWebViewNode and WebView are an iframe, which the embedded Browser.open puts in its screen; a page of another origin is seen only from outside (the table and the events above).
  • The web player — the sheet is a popup and WebView an iframe, as on Web Lite; there is no UIWebViewNode (supported is false, an empty box), so Browser.open({ embedded: true }) rejects there.
  • Desktop — no browser plugin: Browser.supported, UIWebViewNode.supported and WebView.supported are false and open rejects; use openURL.
  • The le.codes viewer app (iOS, Android, the iOS App Clip) has the plugin whatever app.json lists, and no URL scheme of a project: get a return with embedded: true.
  • Headless tests (lecodes render / lecodes test) — no sheet: Browser.open rejects with Browser.open isn't available on this host — it needs the "browser" plugin …; a UIWebViewNode is an empty box (supported false); a WebView exists only when the run names it (--native-view webView), as a placeholder box whose calls all reject and which sends no event.

Pitfalls

  • A WebView's method called before the view is on screen rejects; give the first page as a param (a UIWebViewNode takes calls from the start):

    TypeScript
    const page = WebView(); page.load("https://example.com")   // ✗ no view on screen yet: rejects
    const page = WebView({ url: "https://example.com" })       // ✓
  • bridge, userAgent and ephemeral of a UIWebViewNode are read when it is first shown: write them into UIWebViewNode({ … }), not later.

  • A custom-scheme returnUrl in the sheet on Android never comes back in a project without urlScheme, nor in the le.codes viewer app: open resolves null when the person closes the sheet. Use embedded: true there.

See also