Docs
Web view and video
The web view and the video player embed the platform’s own web engine and media player as ordinary views: web_view and video in Rust (nsh_core::prelude), WebView and Video from nsh in TSX. Because NSH renders with native views, they sit in your layout like any other element: they scroll with their parent, take rounded corners and clipping, and other views can overlap them without layering problems.
| Component | iOS | Android | macOS | Linux | Windows |
|---|---|---|---|---|---|
WebView |
WKWebView | android.webkit.WebView |
WKWebView | WebKitGTK 6.0’s WebKitWebView |
WebView2, in a child window |
Video |
AVPlayerLayer; AVPlayerViewController with controls |
MediaPlayer on a TextureView; MediaController with controls |
AVPlayerLayer; AVKit’s AVPlayerView with controls |
GTK’s media stream (GStreamer) in a GtkPicture; GtkVideo with controls |
Media Foundation’s media engine, frames drawn with Direct2D; NSH’s own control bar with controls |
The frameworks behind them (WebKit, AVFoundation) are loaded the first time an app uses one, so apps that never show a web page or a video do not pay for them at launch.
A video a page plays plays inside the web view on every target, an iPhone included, where WebKit otherwise hands the first frame to the system’s full-screen player (playsinline on the page does not stop it). A page whose own control asks for the whole screen still gets it: on the Apple web views element.requestFullscreen() takes the display, as it does in the browser. Android’s web view has no full screen of its own yet, so a page’s control does nothing there.
On macOS the web view has no scroll view of its own: with scrollable={false} the mouse wheel and the
trackpad scroll the app’s scroll views around it instead of the page, which still scrolls with its keyboard and its
own scripts.
On Linux a web view is a WebKitGTK page drawn inside its view: NSH content over it (a dialog, a sheet)
covers it, and its parents clip it. The webview capability also applies to the navigations of frames there (an
iframe of a host that is not granted stays empty), and scrollable: false stops the page itself from scrolling
(elements inside it still scroll). Apps need WebKitGTK 6.0 installed; a runtime built without it shows a neutral
placeholder. Videos play the formats the installed GStreamer plugins decode; rate is not supported (they
play at 1×), and onEnd only comes for videos that do not loop.
On Windows a web view is a WebView2 control in a child window that follows its view: it is clipped to
its parents and rounded corners, but NSH content drawn over it (a dialog, a sheet) stays under it. It needs the
WebView2 Runtime (part of Windows 11; installed with Edge on Windows 10), else it shows a placeholder;
baseUrl for HTML, scrollable and allowsBackForwardNavigationGestures are not supported. Videos are
ordinary content (clipped, transformed and covered like any view) and play the formats the installed Media Foundation
codecs decode; rate works, and the control bar always shows while controls is on.
#WebView
import { mount, WebView } from "nsh";
import { Window } from "nsh/desktop";
function App() {
return <WebView src="https://en.m.wikipedia.org/wiki/Swift_(programming_language)" style={{ flex: 1 }} />;
}
mount(() => (
<Window id="main">
<App />
</Window>
));use nsh_core::prelude::*;
#[component]
pub fn App() -> impl IntoElement {
web_view("https://en.m.wikipedia.org/wiki/Swift_(programming_language)").flex_1()
}#Sources
A web view shows one of src and html:
| Props | Shows |
|---|---|
src="https://…" |
A web page. |
html="<!doctype html>…" |
HTML from a string, shown instead of src. |
html with baseUrl="https://example.com/" |
HTML whose relative URLs resolve against baseUrl. |
In Rust, web_view(url) shows a page and web_view_html(html, base_url) shows HTML (base_url an Option<&str>); the URL and the HTML can be a signal or a closure, which loads the page again when what it reads changes. Changing src or html loads the new page.
#Props
In Rust each prop is a builder method in snake case (injected_java_script, java_script_enabled, scrollable, user_agent, incognito; injected_java_script_before_content for injectedJavaScriptBeforeContentLoaded, back_forward_gestures for iOS’s allowsBackForwardNavigationGestures) and each event an on_… method (on_navigation_state_change) whose listener gets a WebNavigation (url, title, loading, can_go_back, can_go_forward) or, for on_error and on_message, a &str. Rust also serves the page resources of the app’s own with url_scheme (below).
| Prop | Type | Default | Description |
|---|---|---|---|
src |
string |
The URL of the page to show. | |
html |
string |
Inline HTML, shown instead of src. |
|
baseUrl |
string |
What html’s relative URLs 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. |
|
allowOrigin |
string |
One more origin this web view may show and navigate to besides webview.hosts, for an origin known only while the app runs (a server the user named): scheme://host[:port], http or https, matched exactly (same scheme, host and port; never a subdomain). Needs "runtimeOrigin": true in capabilities.webview; another value is refused with a message. Set in the same render as src, it applies to it; changed later, from the next navigation. Other web views and the windows a page opens do not have it. |
|
allowNavigation |
string[] |
Narrows the hosts this web view may show and navigate to, with the same host patterns as webview.hosts (*, *.example.com, a host name). A page outside them is refused before its request is made and reported to onError with code ERR_ACCESS_DENIED and its url. It never widens the app’s grant, an empty list refuses every web page, and a pattern that does not read is refused with a message. Other schemes (about:blank, the app’s files and URL schemes) keep the app’s own rules. |
|
injectedJavaScript |
string |
Runs after each page loads. | |
injectedJavaScriptBeforeContentLoaded |
string |
Runs before each page’s own scripts. | |
javaScriptEnabled |
boolean |
true |
Pages run scripts. |
scrollable |
boolean |
true |
The user can scroll the page. Off, the page still receives its touches, so its own drag handlers (sliders, sortable lists) work, and its scripts still scroll it. |
userAgent |
string |
The browser’s user agent string. | |
incognito |
boolean |
false |
The pages’ website data lives only as long as the web view, as each platform keeps it (below). Read when the web view is made. |
zoomable |
boolean |
false |
The person can pinch to zoom the page, also past its viewport’s scale limits: built-in zoom without on-screen buttons on Android, the viewport’s limits ignored on iOS, magnification on macOS. Off keeps each platform’s own behavior (Android and macOS do not zoom, iOS zooms as far as the viewport allows, Windows zooms). Read when the web view is made. |
ios={{ allowsBackForwardNavigationGestures }} |
boolean |
iOS: swipe back and forward through the page history. | |
desktop={{ allowsBackForwardNavigationGestures }} |
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 | Payload | When |
|---|---|---|
onLoadStart |
WebViewNavigation |
A page started loading. |
onLoad |
WebViewNavigation |
A page finished loading. |
onError |
{ message, code? } |
Loading failed, the platform shows no web view (code "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM"), or the page’s process ended (code "ERR_NSH_WEBVIEW_TERMINATED"); both below. |
onNavigationStateChange |
WebViewNavigation |
The URL, title, loading state or history changed. |
onMessage |
{ data: string } |
The page posted a message (below). |
WebViewNavigation is { url, title, loading, canGoBack, canGoForward }.
#A browser with back and forward
The web view’s ref (an element_ref() put on it with .element_ref(&web) in Rust, ref in TSX) has reload, go_back / goBack, go_forward / goForward, stop_loading / stopLoading, inject_java_script / injectJavaScript(script), post_message / postMessage(data), load / load({ src, headers }) (below) and send_input / sendInput(input) (below):
import { mount, signal, Text, View, WebView, type WebViewNavigation, type WebViewRef } from "nsh";
import { Window } from "nsh/desktop";
function Browser() {
let web!: WebViewRef;
const nav = signal<WebViewNavigation | null>(null);
const button = (label: string, enabled: boolean, action: () => void) => (
<Text onPress={enabled ? action : undefined} style={{ padding: 12, color: enabled ? "#0969da" : "#8c959f" }}>
{label}
</Text>
);
return (
<View style={{ flex: 1, paddingTop: 50 }}>
<Text style={{ numberOfLines: 1, paddingHorizontal: 12, color: "#57606a" }}>
{nav()?.loading ? "Loading…" : nav()?.title ?? ""}
</Text>
<WebView
ref={web}
src="https://developer.mozilla.org/"
style={{ flex: 1 }}
onNavigationStateChange={(n) => nav.set(n)}
ios={{ allowsBackForwardNavigationGestures: true }}
/>
<View style={{ flexDirection: "row", justifyContent: "space-around" }}>
{button("Back", !!nav()?.canGoBack, () => web.goBack())}
{button("Forward", !!nav()?.canGoForward, () => web.goForward())}
{button("Reload", true, () => web.reload())}
</View>
</View>
);
}
mount(() => (
<Window id="main">
<Browser />
</Window>
));use nsh_core::prelude::*;
pub fn browser() -> impl IntoElement {
let web = element_ref();
let nav = signal(None::<WebNavigation>);
let button = move |label: &'static str, enabled: fn(&WebNavigation) -> bool, action: fn(&ElementRef)| {
let enabled = move || nav.with(|n| n.as_ref().is_some_and(enabled));
text(label)
.p(px(12.0))
.text_color(move || if enabled() { rgb(0x0969da) } else { rgb(0x8c959f) })
.disabled(move || !enabled())
.on_press(move || action(&web))
};
view()
.flex_1()
.pt(px(50.0))
.child(
text(move || {
nav.with(|n| match n {
Some(n) if n.loading => "Loading…".to_owned(),
Some(n) => n.title.clone(),
None => String::new(),
})
})
.number_of_lines(1)
.px(px(12.0))
.text_color(rgb(0x57606a)),
)
.child(
web_view("https://developer.mozilla.org/")
.element_ref(&web)
.flex_1()
.on_navigation_state_change(move |n: &WebNavigation| nav.set(Some(n.clone())))
.back_forward_gestures(true),
)
.child(
view()
.flex_row()
.justify_around()
.child(button("Back", |n| n.can_go_back, |web| web.go_back()))
.child(button("Forward", |n| n.can_go_forward, |web| web.go_forward()))
.child(button("Reload", |_| true, |web| web.reload())),
)
}#Messaging between the page and the app
Pages talk to the app with window.nsh.postMessage(string), which arrives as on_message (onMessage). The app talks to the page with the ref’s post_message (postMessage(string)), which arrives in the page as a message event on window. Messages are strings; send JSON for structured data. Treat what arrives as untrusted data and check it before acting on it: any script the page runs can post, and on Android window.nsh is in every frame of the page, iframes included.
import { mount, signal, Text, View, WebView, type WebViewRef } from "nsh";
import { Window } from "nsh/desktop";
const page = `<!doctype html>
<html><head><meta name="viewport" content="width=device-width"></head>
<body style="font-family: -apple-system, sans-serif; margin: 16px">
<button onclick="window.nsh.postMessage(JSON.stringify({ type: 'hello', at: Date.now() }))">
Post to the app
</button>
<p id="got">Nothing from the app yet.</p>
<script>
window.addEventListener("message", (e) => {
document.getElementById("got").textContent = "The app says: " + e.data;
});
</script>
</body></html>`;
function App() {
let web!: WebViewRef;
const last = signal("");
return (
<View style={{ flex: 1, paddingTop: 50, gap: 12 }}>
<WebView
ref={web}
html={page}
style={{ height: 240 }}
onMessage={(e) => last.set(JSON.parse(e.data).type)}
/>
<Text onPress={() => web.postMessage("hi from nsh")} style={{ padding: 16, color: "#0969da" }}>
Post to the page
</Text>
<Text style={{ paddingHorizontal: 16 }}>Last message: {last()}</Text>
</View>
);
}
mount(() => (
<Window id="main">
<App />
</Window>
));use nsh_core::prelude::*;
const PAGE: &str = r#"<!doctype html>
<html><head><meta name="viewport" content="width=device-width"></head>
<body style="font-family: -apple-system, sans-serif; margin: 16px">
<button onclick="window.nsh.postMessage(JSON.stringify({ type: 'hello', at: Date.now() }))">
Post to the app
</button>
<p id="got">Nothing from the app yet.</p>
<script>
window.addEventListener("message", (e) => {
document.getElementById("got").textContent = "The app says: " + e.data;
});
</script>
</body></html>"#;
#[component]
pub fn App() -> impl IntoElement {
let web = element_ref();
let last = signal(String::new());
view()
.flex_1()
.pt(px(50.0))
.gap(px(12.0))
.child(
web_view_html(PAGE, None)
.element_ref(&web)
.h(px(240.0))
.on_message(move |data: &str| {
let message: serde_json::Value = serde_json::from_str(data).unwrap_or_default();
last.set(message["type"].as_str().unwrap_or_default().to_owned());
}),
)
.child(
text("Post to the page")
.p(px(16.0))
.text_color(rgb(0x0969da))
.on_press(move || web.post_message("hi from nsh")),
)
.child(text(move || format!("Last message: {}", last.get())).px(px(16.0)))
}The ref’s inject_java_script (injectJavaScript(script)) runs code in the current page at any time; injected_java_script and injected_java_script_before_content (injectedJavaScript, injectedJavaScriptBeforeContentLoaded) run on every page load, before or after the page’s own scripts, which is the place to install hooks:
<WebView
src="https://example.com"
injectedJavaScriptBeforeContentLoaded={`window.isNativeApp = true;`}
injectedJavaScript={`window.nsh.postMessage(document.title);`}
onMessage={(e) => console.log("title", e.data)}
/>web_view("https://example.com")
.injected_java_script_before_content("window.isNativeApp = true;")
.injected_java_script("window.nsh.postMessage(document.title);")
.on_message(|title: &str| log::info!("title {title}"))#Resources the app serves
A page can load bytes the app holds (images it has in memory or on disk, a message’s attachments) from a URL scheme
of the app’s own. url_scheme names the scheme and the Rust function that answers its requests; the page refers to
its URLs as to any other (<img src="app-image://img/42">, fetch("app-image://img/42")), and the web engine loads them as it
loads any subresource, bytes as they are, beside the page’s scripts. Images of tens of megabytes load at the speed
of a file.
use nsh_core::{
prelude::*,
web_resource::{WebResource, WebResourceRequest},
};
fn serve(request: WebResourceRequest) {
// On the main thread: hand slow work to a thread and answer from there.
std::thread::spawn(move || match std::fs::read(path_for(request.url())) {
Ok(bytes) if !request.is_cancelled() => request.respond(WebResource::new("image/png", bytes)),
_ => request.fail(),
});
}
web_view_html(html, None).url_scheme("app-image", serve).flex_1()
The handler runs on the platform’s main thread, so it returns at once; the request is answered once, then or later
and from any thread, with respond (bytes and a MIME type) or fail (the image’s error event, a rejected fetch).
A request dropped unanswered fails. When the page no longer needs it (it navigated, the web view went),
is_cancelled() turns true and an answer is dropped. Answers carry Access-Control-Allow-Origin: *, so a page’s
scripts can fetch them whatever the page’s origin, and a Content-Security-Policy names the scheme as any source
(img-src app-image:).
A scheme is a letter followed by letters, digits, +, - or ., and none of the web’s or the system’s (http,
https, file, data, blob, about, …). Several schemes are several calls. Like incognito, the schemes are
read when the web view is made. iOS, macOS, Linux and Windows serve them (WebKit’s WKURLSchemeHandler,
webkit_web_context_register_uri_scheme and WebView2’s custom scheme registrations).
Write the URLs as scheme://host/path (app-image://img/42): every platform hands them to the handler as the page
wrote them. Windows reads a scheme’s URLs as it reads https ones, so that pages can fetch them, and there
app-image:42 reaches the handler as app-image://42/, its first segment a host in lower case.
On Windows, WebView2 registers schemes once for all of the app’s web views, when the first ones are made: a page’s web
views register theirs together, and a scheme that a web view made later brings is not registered, with a warning in
the log: pages still load its URLs as images, but cannot fetch them or read them with XMLHttpRequest. An app that
serves several schemes gives them to the web views it shows first. A failed request answers HTTP 404 there (the
image’s error event; fetch resolves with a response that is not ok), and a page loaded from HTML without a base
URL can load the scheme’s images but cannot fetch it or read it with XMLHttpRequest, since WebView2 lets no
request with an Origin header through from that page’s opaque origin; give such a page a base URL when its scripts
read the scheme.
#Signed-in pages: request headers
To show a page of a service the app has signed in to, send the credential as a header of the page’s request rather than in its URL, where history, logs and Referer would keep it. The ref’s load loads a page with headers on that one request:
web.load({ src: "https://docs.example.com/", headers: { Authorization: `Bearer ${token}` } });use nsh_core::{WebLoad, prelude::*};
fn open(web: &ElementRef, token: &str) {
let headers = vec![("Authorization".to_owned(), format!("Bearer {token}"))];
if let Some(load) = WebLoad::new("https://docs.example.com/", headers) {
web.load(load);
}
}- Only the page’s own request carries the headers: not its images, scripts or other subresources, not its later navigations and not a
reload(), so a credential reaches no other host the page uses. A page that needs it again (a link, a reload) is loaded again withload, with values made for that request (a DPoP proof is bound to its URL). - The page then shows as one from
srcdoes; a later change of thesrcprop loads that page instead. - Its host must be one
webview.hostsallows (webview), as forsrc; otherwise nothing loads and the core logs which host to add. - A header whose name is not an HTTP token or whose value holds a line break throws a
TypeError(WebLoad::newreturnsNone), so one header cannot start another. NSH logs the headers’ names, never their values. - macOS, iOS, Mac Catalyst, Android, Windows, Linux and the GPUI backend send the headers; the browser backend cannot (an iframe has no way to) and does nothing.
#Input as the user’s own
injectJavaScript can only make synthetic events, which a page sees as untrusted (event.isTrusted is false) and some widgets ignore. The ref’s send_input (sendInput(input)) gives the page input as the user’s own hands would, so its events are trusted:
{ type: "click", x, y }clicks a point of the viewport, in CSS pixels (whatgetBoundingClientRect()reports).{ type: "text", text }types the text into what has the page’s focus, a key at a time: each character on the US layout’s key for it, a line break as Enter, and what no US key types (é, CJK, emoji) on no key (codeis"Unidentified").{ type: "key", key }pressesEnter,Tab,EscapeorBackspace.
web.sendInput({ type: "click", x: 120, y: 40 });
setTimeout(() => {
web.sendInput({ type: "text", text: "espresso" });
web.sendInput({ type: "key", key: "Enter" });
}, 50);use nsh_core::{WebInput, WebKey, prelude::*};
use std::time::Duration;
fn search(web: &ElementRef) {
web.send_input(WebInput::Click { x: px(120.0), y: px(40.0) });
let web = *web;
set_timeout(Duration::from_millis(50), move || {
web.send_input(WebInput::Text("espresso".into()));
web.send_input(WebInput::Key(WebKey::Enter));
});
}In Rust these are WebInput::Click { x, y }, WebInput::Text(text) and WebInput::Key(WebKey::Enter).
Trusted input carries user activation (it may open windows, write the clipboard, open the system’s file panel or press a page’s confirm button), so it is a capability of its own: the app needs "webview": { "input": true } in nsh.json’s capabilities (webview), also when it declares none, and the core drops the call otherwise.
Like a click, sendInput takes the keyboard focus for the web view, away from the app’s own Input. The page handles input on its own schedule: a click’s events can still be on their way when the next call starts, so let a click settle (a frame or so) before typing after it. macOS and Windows deliver the input. On Windows a click goes through WebView2’s own mouse input, and text and keys through the browser’s key path, with KeyboardEvent.code naming the US layout’s key (empty for characters no US key types). Linux (WebKitGTK has no way to hand a page trusted input without moving the system’s pointer), iOS and Android ignore it for now.
Before offering anything that depends on it, ask whether it works here: web_input_available() (WebView.inputAvailable()) resolves true only where the platform delivers the input and the app holds webview.input, so it is false on platforms that ignore the call and in apps without the grant.
import { signal, WebView } from "nsh";
const input = signal(false);
WebView.inputAvailable().then((available) => input.set(available));use nsh_core::prelude::*;
let input = signal(false);
spawn(async move { input.set(web_input_available().await) });#Website data
A web view keeps the website data of its pages (cookies, local storage, IndexedDB, the cache) with the app’s, so a
sign-in in one web view is there in the next and after the app restarts. A web view that shows pages the app does not
trust (HTML someone else made, a one-time sign-in) takes incognito: its pages get a store of their own, kept in
memory and gone with the web view.
<WebView src="https://example.com/preview" incognito style={{ flex: 1 }} />web_view("https://example.com/preview").incognito(true).flex_1()incognito is read when the web view is made, so it takes a value in Rust; a later change in TSX keeps the store the
web view has and logs a warning. To switch, show a new web view. Each platform keeps the store this way:
| Platform | An incognito web view’s store |
|---|---|
| iOS, macOS | A non-persistent WKWebsiteDataStore of its own. |
| Linux | An ephemeral WebKit network session of its own. |
| Windows | An InPrivate WebView2 controller. The incognito web views open at the same time share one store in memory, cleared when the last of them closes. |
| Android | Cookies and web storage are the app’s, shared by every web view and kept after it closes. An incognito web view loads without the HTTP cache and saves no form data. |
| Web | The browser’s storage for the page’s origin, as for any iframe. |
#Which sites a web view may show
If your nsh.json declares "capabilities", a web view may only show and navigate to the hosts listed under webview:
{
"capabilities": {
"webview": { "hosts": ["example.com", "*.example.com"] }
}
}
The check covers the web view’s src and every top-level navigation the page makes (links, redirects, location changes); it is decided natively when the platform asks whether a navigation may proceed. A page’s own subresources (scripts, images, frames) are the web content’s business and are not checked. *.example.com matches subdomains only; list example.com as well for the bare domain. An app without a "capabilities" key may show any page. See Sandbox and capabilities.
#When there is no web engine
A web view needs the platform’s web engine, and some installs have none: a Linux runtime built without WebKitGTK, a Windows machine without the WebView2 Runtime, an Android device without an enabled system WebView. The web view then shows a placeholder, and the app can show something else instead (a code block, a link, a file card) at once.
Ask ahead with web_view_available() (WebView.available()): it resolves false where the platform knows from the
start that it shows no web view, and where the app’s capabilities do not grant webview.
import { signal, WebView } from "nsh";
const web = signal(true);
WebView.available().then((available) => web.set(available));use nsh_core::prelude::*;
let web = signal(true);
spawn(async move { web.set(web_view_available().await) });Some engines only fail once a web view starts (WebView2 on Windows), so a web view also tells: its onError comes with
code "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM" as soon as the platform knows.
import { signal, Text, WebView } from "nsh";
function Preview(props: { url: string }) {
const failed = signal(false);
return (
<If when={!failed()} else={<Text>{props.url}</Text>}>
<WebView
src={props.url}
onError={(e) => e.code === "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM" && failed.set(true)}
style={{ flex: 1 }}
/>
</If>
);
}
#When the page’s process ends
A web view’s page runs in a process of its own, which can end while the app runs: it crashed, or the system took
its memory back. The app keeps running and the web view shows no page; its onError comes with code
"ERR_NSH_WEBVIEW_TERMINATED" (Rust: .on_process_terminated, the message). The ref’s reload(), load() or a new
src / html shows a page again (Android makes a new WebView for it). iOS, macOS, Linux and Android report it.
import { WebView, type WebViewRef } from "nsh";
function Diagram(props: { html: string }) {
let web!: WebViewRef;
return (
<WebView
ref={web}
html={props.html}
onError={(e) => e.code === "ERR_NSH_WEBVIEW_TERMINATED" && web.reload()}
style={{ flex: 1 }}
/>
);
}
#Video
import { mount, signal, Text, Video, type VideoRef, View } from "nsh";
import { Window } from "nsh/desktop";
function Player() {
let video!: VideoRef;
const paused = signal(true);
const time = signal("");
return (
<View style={{ flex: 1, justifyContent: "center", padding: 16, gap: 12 }}>
<Video
ref={video}
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
paused={paused()}
repeat
style={{ height: 220, borderRadius: 12, overflow: "hidden", backgroundColor: "#000000" }}
onProgress={(e) => time.set(`${e.currentTime.toFixed(1)} / ${e.duration.toFixed(1)} s`)}
onEnd={() => paused.set(true)}
/>
<View style={{ flexDirection: "row", gap: 16, alignItems: "center" }}>
<Text onPress={() => paused.set(!paused())} style={{ color: "#0969da", fontWeight: "600" }}>
{paused() ? "Play" : "Pause"}
</Text>
<Text onPress={() => video.seek(0)} style={{ color: "#0969da" }}>
Restart
</Text>
<Text style={{ color: "#57606a" }}>{time()}</Text>
</View>
</View>
);
}
mount(() => (
<Window id="main">
<Player />
</Window>
));use nsh_core::prelude::*;
pub fn player() -> impl IntoElement {
let player = element_ref();
let paused = signal(true);
let time = signal(String::new());
let link = |label: &'static str| text(label).text_color(rgb(0x0969da));
view()
.flex_1()
.justify_center()
.p(px(16.0))
.gap(px(12.0))
.child(
video("https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4")
.element_ref(&player)
.paused(paused)
.repeat(true)
.object_fit(ResizeMode::Contain)
.h(px(220.0))
.rounded(px(12.0))
.overflow_hidden()
.bg(rgb(0x000000))
.on_progress(move |e: &VideoProgress| {
time.set(format!("{:.1} / {:.1} s", e.current_time, e.duration))
})
.on_end(move || paused.set(true)),
)
.child(
view()
.flex_row()
.gap(px(16.0))
.items_center()
.child(
text(move || if paused.get() { "Play" } else { "Pause" })
.text_color(rgb(0x0969da))
.font_weight(FontWeight::SEMIBOLD)
.on_press(move || paused.update(|p| *p = !*p)),
)
.child(link("Restart").on_press(move || player.seek(0.0)))
.child(text(move || time.get()).text_color(rgb(0x57606a))),
)
}Playback is controlled by props: set paused, muted, volume and rate from signals and the player follows. Unpausing a video that played to its end plays it again from the start. The ref has seek(seconds).
In Rust, video(url) makes the player (the URL a value, a signal or a closure) and each prop is a builder method in snake case (paused, repeat(true), object_fit(ResizeMode::Contain) (the objectFit style), progress_interval for progressUpdateInterval); on_load gets a VideoInfo (duration, size), on_progress a VideoProgress (current_time, duration) and on_buffer a bool.
| Prop | Type | Default | Description |
|---|---|---|---|
src |
string |
The video’s URL. | |
poster |
string |
An image shown while the video loads, until its first frame is ready. | |
paused |
boolean |
false |
Playback is paused. |
muted |
boolean |
false |
No sound. |
volume |
number |
1 |
0..1. |
rate |
number |
1 |
The playback speed. |
repeat |
boolean |
false |
Plays again from the start at the end. |
objectFit (style), object-* classes |
"cover" | "contain" | "fill" | "none" | "scale-down" |
"contain" |
How the picture fits the view, as CSS’s object-fit (class="object-cover"). |
controls |
boolean |
false |
The platform’s playback controls. |
progressUpdateInterval |
number |
250 |
Milliseconds between onProgress events. |
| Event | Payload | When |
|---|---|---|
onLoadStart |
Loading started. | |
onLoad |
{ duration, size } |
The video is ready: its length in seconds and its size. |
onProgress |
{ currentTime, duration } |
While playing, every progressUpdateInterval ms. |
onBuffer |
{ isBuffering } |
Playback stalled waiting for data, or resumed. |
onEnd |
Playback reached the end. | |
onError |
{ message } |
Loading or playback failed. |
With controls, the platform draws its own play button, scrubber and full-screen button. Without, draw your own with views over or below the video; since the video is a native view in your layout, overlays work naturally:
<View style={{ height: 220 }}>
<Video src={url} paused={paused()} style={{ flex: 1 }} />
<View
onPress={() => paused.set(!paused())}
style={{ position: "absolute", top: 0, left: 0, right: 0, bottom: 0, alignItems: "center", justifyContent: "center" }}
>
<If when={paused()}>
<Text style={{ fontSize: 48, color: "#ffffff" }}>▶</Text>
</If>
</View>
</View>view()
.h(px(220.0))
.child(video(url).paused(paused).flex_1())
.child(
view()
.absolute()
.inset_0()
.items_center()
.justify_center()
.on_press(move || paused.update(|p| *p = !*p))
.child(when(move || paused.get(), || {
text("▶").text_size(px(48.0)).text_color(rgb(0xffffff))
})),
)Video sources are network requests: with declared capabilities, the video’s host must be allowed under network in nsh.json, as for fetch and remote images. A refused source shows nothing, and the refusal is logged once with the key to add.
#Related
WebViewandVideo: the element references.- Sandbox and capabilities:
webviewandnetworkgrants. - Native components: embedding other native views your host app provides.