Elements

WebView

A web view shows a web page, or HTML you pass in, inside the app: WKWebView on iOS and Mac Catalyst, android.webkit.WebView on Android. Because NSH renders with native views, a web view sits in the layout like any other view, in order with the views around it. Rust makes one with web_view(url) or web_view_html(html, base_url), TSX with <WebView> from nsh.

el-web-view.tsx
el-web-view.tsxLive
import { mount, signal, Text, View, WebView, type WebViewNavigation, type WebViewRef } from "nsh";
import { platform, windowSize } from "nsh";
import { button, buttonText, ui, sectionSurface } from "./palette";

// The page: a button that posts to the app, and a line that shows what the
// app posts back.
const page = (c: ReturnType<typeof ui>) => `<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Inline page</title>
<style>
  body { font: 15px system-ui, sans-serif; margin: 0; padding: 16px; background: ${c.page}; color: ${c.text}; }
  button { font: inherit; font-weight: 600; padding: 10px 14px; border-radius: 10px; border: 1px solid ${c.border}; background: ${c.accent}; color: ${c.page}; }
  .muted { color: ${c.muted}; }
  #got { margin-top: 12px; }
  #box { margin-top: 12px; height: 48px; border-radius: 10px; background: ${c.border}; transition: background 0.3s; }
</style>
<p class="muted">This is HTML in a web view.</p>
<button id="post">postMessage to the app</button>
<p id="got" class="muted">Nothing from the app yet.</p>
<div id="box"></div>
<script>
  let taps = 0;
  document.getElementById("post").onclick = () =>
    window.nsh.postMessage("tap " + ++taps + " from the page");
  window.addEventListener("message", (e) => { document.getElementById("got").textContent = "App says: " + e.data; });
</script>`;

function Button(props: { label: string; onPress: () => void }) {
  return (
    <View
      onPress={props.onPress}
      {...button()}
    >
      <Text style={buttonText()}>{props.label}</Text>
    </View>
  );
}

const colors = () => [ui().accent, ui().info, ui().violet, ui().down, ui().warn];

function App() {
  const messages = signal<string[]>([]);
  const nav = signal<WebViewNavigation | null>(null);
  const sent = signal(0);
  let painted = 0;
  let web!: WebViewRef;
  const wide = () => windowSize().width >= 700;

  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>web-view</Text>
      <View style={{ flex: 1, flexDirection: wide() ? "row" : "column", gap: 16 }}>
        <WebView
          ref={web}
          html={page(ui())}
          // Runs after each load: the page reports its title.
          injectedJavaScript={`window.nsh.postMessage("loaded: " + document.title)`}
          onLoad={(e) => nav.set(e)}
          onMessage={(e) => messages.set([e.data, ...messages()].slice(0, 4))}
          style={{ flex: 1, minHeight: 240, borderRadius: 14, overflow: "hidden", borderWidth: 1, borderColor: ui().border }}
        />
        <View style={{ gap: 12, width: wide() ? 320 : undefined }}>
          <Text style={{ color: ui().muted }}>
            {platform.desktop ? "Click" : "Tap"} the button in the page to post to the app; these buttons call the ref's methods.
          </Text>
          <View style={{ flexDirection: "row", flexWrap: "wrap", gap: 8 }}>
            <Button
              label="postMessage"
              onPress={() => {
                sent.update((n) => n + 1);
                web.postMessage(`hello #${sent()}`);
              }}
            />
            <Button
              label="injectJavaScript"
              onPress={() => {
                const color = colors()[painted++ % colors().length];
                web.injectJavaScript(`document.getElementById("box").style.background = "${color}"`);
              }}
            />
            <Button label="reload" onPress={() => web.reload()} />
          </View>
          <View style={{ ...sectionSurface({ padded: true }), gap: 4 }}>
            <Text style={{ color: ui().muted, fontSize: 12 }}>onLoad</Text>
            <Text style={{ numberOfLines: 1, color: ui().text, fontFamily: "monospace", fontSize: 13 }}>
              {nav() ? `title "${nav()!.title}"` : "…"}
            </Text>
            <Text style={{ color: ui().muted, fontSize: 12, marginTop: 6 }}>onMessage, newest first</Text>
            <Each of={messages()}>
              {(m) => <Text style={{ color: ui().text, fontFamily: "monospace", fontSize: 13 }}>{m()}</Text>}
            </Each>
          </View>
        </View>
      </View>
    </View>
  );
}

mount(App);
use nsh_core::prelude::*;

fn browser() -> impl IntoElement {
    let title = signal(SharedString::from("Loading…"));
    view()
        .flex_1()
        .child(text(title).number_of_lines(1))
        .child(
            web_view("https://example.com")
                .flex_1()
                .on_navigation_state_change(move |e: &WebNavigation| title.set(e.title.clone().into())),
        )
}

In TSX a web view takes one of src and html (see the WebView API). The web view and video guide covers messaging patterns and capabilities.

#Props

A web view takes the props of a view (it has no children) plus:

Prop Rust Type Default Description
src web_view(url) string The URL of the page to show.
html web_view_html(html, base_url), .html(html, base_url) string Inline HTML, shown instead of src.
baseUrl base_url of web_view_html / .html string What html’s relative links resolve against. It needs the same grant as a page there (webview.hosts); without it the HTML loads with no base URL and onError reports ERR_ACCESS_DENIED.
injectedJavaScript .injected_java_script(..) string Runs after each page loads.
injectedJavaScriptBeforeContentLoaded .injected_java_script_before_content(..) string Runs before each page’s own scripts.
userAgent .user_agent(..) string The browser’s user agent string.
javaScriptEnabled .java_script_enabled(..) boolean true Pages run scripts.
scrollable .scrollable(..) boolean true The user can scroll the page.
incognito .incognito(bool) boolean false The pages’ website data (cookies, storage, the cache) lives only as long as the web view, apart from the app’s; on Android the web view loads without the HTTP cache and saves no form data (website data). Read when the web view is made.
ios key Rust Type Description
allowsBackForwardNavigationGestures .back_forward_gestures(..) boolean Swipe from the edges to go back and forward.
desktop key Rust Type Description
allowsBackForwardNavigationGestures .back_forward_gestures(..) boolean macOS: swipe with two fingers on the trackpad to go back and forward; Windows: swipe on a touchscreen; Linux: swipe on the touchpad.

#Events

Event Rust Payload When
onLoadStart .on_load_start WebViewNavigation A page started loading.
onLoad .on_load WebViewNavigation A page finished loading.
onError .on_error { message, code? } (&str, the message) Loading failed; code is "ERR_ACCESS_DENIED" for a page, html or baseUrl the app’s capabilities do not grant, and "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM" where the platform shows no web view (Rust: also .on_unavailable, the message).
onNavigationStateChange .on_navigation_state_change WebViewNavigation The URL, title, loading state or history changed.
onMessage .on_message { data: string } (&str) The page called window.nsh.postMessage(data).
onDownload WebViewDownload A download started, finished or failed (macOS).

WebViewNavigation is { url, title, loading, canGoBack, canGoForward }; in Rust WebNavigation with url, title, loading, can_go_back and can_go_forward.

WebView.available() (Rust web_view_available()) resolves whether a web view shows a page here: false where the platform has no web engine or the app’s capabilities do not grant webview (When there is no web engine).

WebViewDownload is { state, id, url, filename, path, bytes?, message? }: state is "started", "finished" (with the file’s bytes) or "failed" (with its message). With an onDownload listener, what the page downloads (an attachment, a type the web view does not show, a download link) is saved in the app’s data directory as downloads/<id>/<filename>, where path points, and the app reads it with fs/promises.

On macOS, adding the listener lets any loaded page allowed by the webview capability save downloads automatically. The app is responsible for its storage budget and for removing completed files from downloads/ when it has finished using them. Removing the web view cancels downloads in progress and removes their partial directories. Downloads report through onDownload; converting a navigation into a download keeps onError for actual navigation failures. Filenames have control characters and bidirectional formatting controls removed, and long names are shortened to 200 bytes while preserving an extension that fits.

#Ref methods

Method Rust Description
reload() reload() Reloads the page.
goBack() / goForward() go_back() / go_forward() Moves in the page’s history.
stopLoading() stop_loading() Stops loading.
injectJavaScript(script) inject_java_script(script) Runs JavaScript in the page.
postMessage(data) post_message(data) Sends a string to the page, which receives a message event on window.
load({ src, headers }) load(WebLoad::new(src, headers)?) Loads src with headers (e.g. Authorization) on the page’s own request only, not its subresources or later navigations (guide).

#Messaging

The app and the page exchange strings. The page posts with window.nsh.postMessage(data); the app posts with the ref’s postMessage(data) (post_message(..) in Rust). Send JSON for structured data.

use nsh_core::prelude::*;

const PAGE: &str = r#"<!doctype html>
<meta name="viewport" content="width=device-width">
<button onclick="window.nsh.postMessage('hello from the page')">Post to the app</button>
<p id="got"></p>
<script>
  window.addEventListener("message", (e) => { document.getElementById("got").textContent = e.data; });
</script>"#;

fn bridge() -> impl IntoElement {
    let message = signal(String::new());
    let web = element_ref();
    view()
        .gap_3()
        .child(
            web_view_html(PAGE.to_string(), None)
                .element_ref(&web)
                .h(px(200.0))
                .on_message(move |data: &str| message.set(data.to_string())),
        )
        .child(
            text(move || format!("Post to the page · got: {}", message.get()))
                .on_press(move || web.post_message("hi from the app")),
        )
}

#Capabilities

When the app declares capabilities in nsh.json, a web view shows and navigates to the hosts listed under webview. A src on another host, or html in an app without webview, shows an empty view; a baseUrl on another host is dropped, and the HTML loads without it; a top-level navigation to another host (a link the user taps) is cancelled natively. Each reports onError with code "ERR_ACCESS_DENIED".

{
  "capabilities": {
    "webview": { "hosts": ["example.com", "*.example.com"] }
  }
}

#Platform notes

  • iOS loads WebKit the first time a web view is created, so it costs an app something only once it shows one.
  • On macOS onDownload saves downloads with WebKit’s WKDownload.
  • On Android the page’s postMessage calls arrive on a background thread and are forwarded to the app in order.
  • To round the corners of a web view, give it a corner radius and overflow: "hidden" (.overflow_hidden()).