moonview

Direct native WebView embedding for MoonBit.

webview
webview2
webkitgtk
windows
macos
linux
openharmony
arkweb
desktop
moon add Nanaloveyuki/moonview@0.1.0-beta.8
Download zip
Version
0.1.0-beta.8
License
Apache-2.0
Last updated
2 days ago
Downloads
304

Dependencies

README

#moonview

moonview embeds a native platform WebView into a MoonBit application's existing window. It does not create a top-level window or run an event loop. The host owns those responsibilities; moonview owns the child WebView.

#Install

Add the preview package to a native MoonBit module:

moon add Nanaloveyuki/moonview@0.1.0-beta.8

Add the package import in the consumer's moon.pkg, then refer to it as @moonview:

import {
"Nanaloveyuki/moonview",
}

The package-level reference is src/README.mbt.md.

#Host Contract

Create the WebView on the UI thread that owns its native parent, keep that platform's event loop running, resize it with the parent, and destroy it before the parent is destroyed. Every command, including destroy, must run on that same UI thread; Moonview does not provide a cross-thread dispatcher.

Platformparent_handle passed to WebView::create
WindowsA caller-owned HWND on an STA UI thread
macOSA caller-owned NSView* on the main thread
LinuxA caller-owned GtkFixed* on the GTK UI thread
OpenHarmonyAn ArkUI-owned Web component identified by webTag

This raw-handle boundary is intentional so a window-management library can own native window creation and event dispatch. Popup and window.open requests are denied by default. A host can instead redirect an individual request into the existing WebView; Moonview never creates a top-level window for page content.

#Create A WebView

Use Ready before issuing work that requires a loaded native view. initial_html takes precedence when both initial-content fields are set.

let options = @moonview.WebViewOptions::new(
bounds=@moonview.Rect::new(x=0, y=0, width=800, height=600),
initial_url="https://example.com",
initialization_script="console.log('moonview initialized')",
on_event=event => match event {
@moonview.WebViewEvent::Ready => println("webview ready")
@moonview.WebViewEvent::CreationFailed(_error) => println("create failed")
@moonview.WebViewEvent::ProcessFailed(_error) => println("browser process failed")
_ => ()
},
on_navigation=_url => @moonview.NavigationDecision::Allow,
on_new_window=_url => @moonview.NewWindowDecision::Deny,
)

match @moonview.WebView::create(parent_handle, options) {
Ok(view) => ignore(view.set_visible(true))
Err(_error) => abort("WebView creation rejected")
}

Resize the child with the host window and dispose it during host teardown:

ignore(view.set_bounds(@moonview.Rect::new(x=0, y=0, width=1024, height=768)))
ignore(view.navigate("https://example.com/docs"))
ignore(view.destroy())

Control methods return Ok(()) only when the native backend accepts or queues the command for a live view. Page navigation and JavaScript execution remain asynchronous; observe their final outcomes through WebViewEvent.

ProcessFailed is terminal. Destroy the failed WebView on its owner UI thread, then create a replacement explicitly. Moonview does not recreate browser processes in the background.

#Browser Data Contexts

The default WebView::create uses the shared persistent context. Reuse a WebContext when multiple views must share browser data, and pass it to create_in_context:

let context = @moonview.WebContext::persistent(data_directory="F:/app-data/moonview")
match @moonview.WebView::create_in_context(context, parent_handle, options) {
Ok(view) => ignore(view.set_visible(true))
Err(_error) => abort("WebView creation rejected")
}

Custom data directories are supported on Windows and Linux. Ephemeral contexts are supported on macOS and Linux. Unsupported combinations return Unsupported instead of falling back to another browser profile.

#OpenHarmony ArkWeb (Experimental)

OpenHarmony does not expose native creation of an arbitrary child WebView. The ArkUI host creates the Web component, selects its source and permissions, and then attaches Moonview using that component's stable webTag on the ArkUI UI thread:

let options = @moonview.OhosAttachOptions::new(
on_event=event => match event {
@moonview.WebViewEvent::Ready => println("ArkWeb controller attached")
_ => ()
},
)

match @moonview.WebView::attach_ohos("main-web", options) {
Ok(view) => {
ignore(view.reload())
// API 12 executes this without a ScriptResult callback.
ignore(view.eval("console.log('from MoonBit')", "startup"))
}
Err(_error) => abort("ArkWeb attach rejected")
}

This first adapter targets OpenHarmony API 12 and supports attach, reload, fire-and-forget eval, and detachment through destroy. ArkUI retains source, layout, visibility, focus, and media-permission ownership. Navigation, HTML loading, init scripts, history, zoom, page messaging, custom schemes, and script-result callbacks return Unsupported until their thread-safe native adapters are implemented. destroy detaches Moonview only; it never destroys the ArkUI component.

#Page Communication

The injected page bridge exposes window.moonview.postMessage(string). Handle PageMessage in on_event, and send data to the page with post_message. Payloads are UTF-8 strings; applications define their own JSON or RPC protocol. When native code posts to the page, window.moonview.onmessage receives an object with the UTF-8 payload in event.data on every desktop backend.

match event {
@moonview.WebViewEvent::PageMessage(message) => println("page: \{message}")
@moonview.WebViewEvent::ScriptResult(id, value) => println("\{id}: \{value}")
_ => ()
}

ignore(view.post_message("host-ready"))
ignore(view.eval("document.title", "document-title"))

window.moonview.onmessage = event => { console.log(event.data) }

eval reports JSON text through ScriptResult; JavaScript undefined is reported as null.

#Resource Limits

Each desktop WebView defaults to 256 commands queued before readiness, 4 MiB of queued command storage, and a 4 MiB custom-scheme request body limit. Pass WebViewResourceLimits through WebViewOptions to configure these values; 0 disables an individual limit and negative values reject creation with NativeFailure. Windows, macOS, and Linux enforce this policy.

let limits = @moonview.WebViewResourceLimits::new(
max_pending_commands=64,
max_pending_command_bytes=1024 * 1024,
max_protocol_request_body_bytes=1024 * 1024,
)
let options = @moonview.WebViewOptions::new(
bounds=@moonview.Rect::new(x=0, y=0, width=800, height=600),
resource_limits=limits,
)

#Serve Application Resources

Register application-owned schemes before the first WebView::create. Native backends emit ProtocolRequest events containing the method, URI, headers, and binary body. Retain the owning WebView in the callback state, then answer the request with respond_protocol before its 30-second deadline.

ignore(@moonview.register_custom_scheme("app"))

let response = @moonview.ProtocolResponse::new(
status=200,
headers=[@moonview.HttpHeader::new(name="Content-Type", value="text/html")],
body=b"<!doctype html><title>moonview</title>",
)

// In the WebView event callback:
// @moonview.WebViewEvent::ProtocolRequest(request) =>
// ignore(view.respond_protocol(request.id, response))

Use URLs such as app://ui/index.html. Windows and WebKitGTK register custom schemes as secure origins; WKWebView uses its public URL-scheme handler. Unanswered or cancelled requests emit ProtocolCancelled. Requests whose body exceeds the configured limit receive HTTP 413 locally and do not produce a ProtocolRequest event.

#Permissions And Diagnostics

Camera and microphone requests are denied by default. Supply on_media_permission only when the application can make a synchronous policy decision for the requesting origin. Other browser permission categories are not part of the cross-platform API.

open_devtools is available on Windows and Linux; WKWebView returns Unsupported. open_print_dialog uses the platform print UI and may be unsupported on older platform runtimes.

#Native File Dialogs

WebView::show_file_dialog presents a platform-native dialog from the owning UI thread. Windows supports file open, multi-file open, save, and directory selection. Other backends currently return Unsupported explicitly.

match view.show_file_dialog(
@moonview.FileDialogOptions::new(
kind=@moonview.FileDialogKind::OpenFile,
title=Some("Open document"),
filters=[
@moonview.FileDialogFilter::new(
name="Text files",
extensions=["txt", "md"],
),
],
),
) {
Ok(@moonview.FileDialogResult::Cancelled) => ()
Ok(@moonview.FileDialogResult::Selected(paths)) => println(paths)
Err(error) => println(error)
}

The selected paths are native host data. Frameworks embedding MoonView should apply their own capability policy before forwarding a selection to page code. For an interactive Windows verification in this checkout, run:

$env:MOONVIEW_FILE_DIALOG_SMOKE = "1" moon run src/examples/windows_smoke

Cancel the dialog or select a MoonBit source file; either normal outcome lets the smoke contract complete. Omit the environment variable in CI.

#Platform Prerequisites

  • Windows: Visual Studio Build Tools and the Edge WebView2 Runtime. On the first native build, Moonview downloads the official Microsoft WebView2 SDK 1.0.4078.44, verifies its pinned SHA-256 digest, and atomically extracts it under %LOCALAPPDATA%\moonview\webview2\1.0.4078.44. Parallel builds share a directory lock. Set MOONVIEW_WEBVIEW2_CACHE_DIR to move the cache, or set MOONVIEW_WEBVIEW2_SDK_DIR to use an existing SDK without downloading. MOONVIEW_WEBVIEW2_INCLUDE and MOONVIEW_WEBVIEW2_LOADER_LIB remain the most specific overrides. Set MOONVIEW_WEBVIEW2_ARCH to x64, x86, or arm64; it defaults to x64. Automatic extraction uses tar from PATH.
  • macOS: Xcode Command Line Tools. WKWebView is supplied by the operating system.
  • Linux: GTK 3 and the webkit2gtk-4.1 development package available through pkg-config. The Linux smoke also works through WSLg.
  • OpenHarmony: an app manifest declaring SystemCapability.Web.Webview.Core and the user-supplied ArkWeb NDK. Set MOONVIEW_OHOS_ARKWEB_SDK_DIR (or MOONVIEW_OHOS_NDK_HOME) to a directory containing arkweb_interface.h and libohweb.so; alternatively set both MOONVIEW_OHOS_ARKWEB_INCLUDE and MOONVIEW_OHOS_ARKWEB_LIB. Moonview does not vendor or read SDK files from ref/.
  • Android (experimental): import Nanaloveyuki/moonview/android, which depends only on the optional Nanaloveyuki/ajni/webview feature. Attach ajni's Kotlin host to an Activity-owned FrameLayout before creating a view, and set MOONVIEW_NATIVE_BACKEND=android for the MoonBit build. The adapter provides a single HTTPS asset origin, document-start scripts, structured page messages, asynchronous asset responses, operation-correlated errors, and resource limits. See src/android/README.mbt.md for CMake integration and usage.

#Verify A Checkout

moon fmt --check moon check --target native moon test --target native node --test tests/build.test.js .\scripts\test-windows.ps1 .\scripts\test-windows.ps1 -WebView2Sdk F:\path\to\Microsoft.Web.WebView2.1.0.x

macOS and Fedora native smoke coverage runs in GitHub Actions.

#Contributing

See CONTRIBUTING.md for development setup, validation, and pull request requirements.

#Preview Compatibility

0.1.0-beta.8 is an API preview. Compatibility may change before stable 0.1.0, particularly once a concrete window-host integration contract exists.

#moonview

moonview is the native-only package for embedding a platform WebView in a caller-owned native container. The host supplies the parent handle, owns the UI thread and event loop, resizes the child, and destroys the child before its parent. Every WebView command must run on that owner UI thread; Moonview does not provide cross-thread dispatch.

#Minimal Use

let options = WebViewOptions::new(
bounds=Rect::new(x=0, y=0, width=800, height=600),
initial_html="<!doctype html><title>moonview</title>",
on_event=event => match event {
WebViewEvent::Ready => println("ready")
WebViewEvent::CreationFailed(_error) => println("failed")
WebViewEvent::ProcessFailed(_error) => println("browser process failed")
_ => ()
},
)

match WebView::create(parent_handle, options) {
Ok(view) => ignore(view.post_message("host-ready"))
Err(_error) => abort("create rejected")
}

Control methods return Ok(()) only after the native backend accepts or queues the command for a live view. Navigation and JavaScript outcomes remain asynchronous and are reported through WebViewEvent.

ProcessFailed is terminal. On WebView2 runtime failures, Moonview stops accepting commands for that view. Destroy it on its owner UI thread, then create a replacement explicitly; Moonview never attempts background recovery.

#Resource Limits

Desktop backends limit each WebView to 256 commands queued before readiness, 4 MiB of queued command storage, and 4 MiB per custom-scheme request body. Configure or disable individual limits with WebViewResourceLimits; 0 disables one limit, while negative values cause WebView::create to return NativeFailure. The limits currently apply to Windows, macOS, and Linux.

///|
let options = WebViewOptions::new(
bounds=Rect::new(x=0, y=0, width=800, height=600),
resource_limits=WebViewResourceLimits::new(
max_pending_commands=64,
max_pending_command_bytes=1024 * 1024,
max_protocol_request_body_bytes=1024 * 1024,
),
)

Use WebViewEvent::Ready before relying on a loaded document. Page code sends UTF-8 strings with window.moonview.postMessage(...); native code receives PageMessage and sends strings with WebView::post_message(...). Page-side window.moonview.onmessage receives an object whose data property contains the UTF-8 message on every desktop backend.

#Browser Data Contexts

WebView::create uses the shared persistent context. Reuse a WebContext when multiple views must share browser data:

let context = @moonview.WebContext::persistent(data_directory="F:/app-data/moonview")
match @moonview.WebView::create_in_context(context, parent_handle, options) {
Ok(view) => ignore(view.set_visible(true))
Err(_error) => abort("WebView creation rejected")
}

Custom data directories are supported on Windows and Linux. Ephemeral contexts are supported on macOS and Linux. Unsupported combinations return Unsupported rather than selecting another browser profile.

#OpenHarmony ArkWeb

OpenHarmony hosts Web in ArkUI rather than accepting an arbitrary native parent handle. Create that component in ArkUI, then attach on its UI thread by its stable webTag:

let options = OhosAttachOptions::new(
on_event=event => match event {
WebViewEvent::Ready => println("ArkWeb attached")
_ => ()
},
)

match WebView::attach_ohos("main-web", options) {
Ok(view) => {
ignore(view.reload())
ignore(view.eval("console.log('moonview')", "startup"))
}
Err(_error) => abort("ArkWeb attach rejected")
}

The experimental API 12 adapter supports attach, reload, fire-and-forget eval, and detachment. ArkUI owns source, layout, visibility, and permissions; the remaining desktop-style controls return Unsupported. destroy detaches Moonview and does not destroy the ArkUI Web component.

#Application Resources

Call register_custom_scheme(...) before the first WebView::create, then respond to each ProtocolRequest with WebView::respond_protocol(...). The request callback carries method, URI, headers, and binary body data; unanswered requests are cancelled after 30 seconds. Oversized request bodies are answered with HTTP 413 locally and are not dispatched to MoonBit.

#Permissions

Camera and microphone requests are denied unless on_media_permission returns MediaPermissionDecision::Allow. Other browser permission kinds are not part of this cross-platform package API.

#Native File Dialogs

WebView::show_file_dialog presents a platform-native dialog from the owning UI thread. Windows supports file open, multi-file open, save, and directory selection. Other backends currently return Unsupported explicitly.

match view.show_file_dialog(
FileDialogOptions::new(
kind=FileDialogKind::OpenFile,
title=Some("Open document"),
filters=[
FileDialogFilter::new(
name="Text files",
extensions=["txt", "md"],
),
],
),
) {
Ok(FileDialogResult::Cancelled) => ()
Ok(FileDialogResult::Selected(paths)) => println(paths)
Err(error) => println(error)
}

The selected paths are native host data. Frameworks embedding MoonView should apply their own capability policy before forwarding a selection to page code.

#Main Entry Points

  • WebViewOptions::new(...) configures creation callbacks and initial content.
  • on_new_window denies page-created windows by default, or can return NewWindowDecision::NavigateCurrent to redirect the requesting WebView.
  • WebView::create(...) embeds an asynchronously-created native child view.
  • WebView::set_bounds(...), navigate(...), eval(...), and post_message(...) control a live view.
  • WebView::show_file_dialog(...) presents a native file or directory dialog.
  • WebView::destroy(...) releases the native child before the host parent.
  • register_custom_scheme(...) and WebView::respond_protocol(...) serve application-owned resources.

See the repository README for platform prerequisites and host-handle details.

#
FileDialogFilter

pub(all) struct FileDialogFilter {
name : String
extensions : Array[String]
} derive(Eq,
Debug
)

A user-facing name and the extensions accepted by a file dialog. Extensions do not include a leading dot or wildcard.

#
FileDialogFilter::new

fn FileDialogFilter::new(name~ : String, extensions~ : Array[String]) -> FileDialogFilter

#
FileDialogKind

pub(all) enum FileDialogKind {
OpenFile
OpenFiles
SaveFile
PickDirectory
} derive(Eq,
Debug
)

The native dialog operation to present for a WebView.

#
FileDialogOptions

pub(all) struct FileDialogOptions {
kind : FileDialogKind
title : String?
filters : Array[FileDialogFilter]
default_name : String?
initial_directory : String?
} derive(Eq,
Debug
)

Options for a native file dialog owned by a WebView's native container.

#
FileDialogOptions::new

fn FileDialogOptions::new(kind~ : FileDialogKind, title? : String?, filters? : Array[FileDialogFilter], default_name? : String?, initial_directory? : String?) -> FileDialogOptions

#
FileDialogResult

pub(all) enum FileDialogResult {
Cancelled
Selected(Array[String])
} derive(Eq,
Debug
)

The outcome of a native file dialog. Cancelled is a normal user action.

#
HttpHeader

pub(all) struct HttpHeader {
name : String
value : String
} derive(Eq,
Debug
)

A single HTTP header in a custom-scheme request or response.

#
HttpHeader::new

fn HttpHeader::new(name~ : String, value~ : String) -> HttpHeader

#
MediaPermissionDecision

pub(all) enum MediaPermissionDecision {
Allow
Deny
} derive(Eq,
Debug
)

The decision synchronously returned to a native media-permission callback.

#
MediaPermissionKind

pub(all) enum MediaPermissionKind {
Camera
Microphone
CameraAndMicrophone
Unknown(Int)
} derive(Eq,
Debug
)

A media capture category requested by page content.

#
MediaPermissionRequest

pub(all) struct MediaPermissionRequest {
kind : MediaPermissionKind
origin : String
} derive(Eq,
Debug
)

A synchronous request to access local media devices from an origin.
pub(all) enum NavigationDecision {
Allow
Deny
} derive(Eq,
Debug
)

The decision synchronously returned to a native navigation callback.
pub(all) struct NavigationState {
url : String
can_go_back : Bool
can_go_forward : Bool
} derive(Eq,
Debug
)

The most recently observed document URL and history availability.
fn NavigationState::new(url? : String, can_go_back? : Bool, can_go_forward? : Bool) -> NavigationState

#
NewWindowDecision

pub(all) enum NewWindowDecision {
Deny
NavigateCurrent
} derive(Eq,
Debug
)

The decision synchronously returned when page content requests a new browser window. Moonview never creates a top-level native window itself.

#
OhosAttachOptions

pub(all) struct OhosAttachOptions {
on_event : (WebViewEvent) -> Unit
}

Configuration for attaching to an ArkUI-owned OpenHarmony Web component.

The ArkUI host owns the component's source, layout, visibility, and browser permissions. This API is separate from WebViewOptions so unsupported creation settings cannot be silently ignored.

#
OhosAttachOptions::new

fn OhosAttachOptions::new(on_event? : (WebViewEvent) -> Unit) -> OhosAttachOptions

#
ProtocolRequest

pub(all) struct ProtocolRequest {
id : String
scheme : String
http_method : String
uri : String
headers : Array[HttpHeader]
body : Bytes
} derive(Eq,
Debug
)

A pending custom-scheme request. body is unmodified binary request data.

#
ProtocolResponse

pub(all) struct ProtocolResponse {
status : Int
headers : Array[HttpHeader]
body : Bytes
} derive(Eq,
Debug
)

A response to a pending custom-scheme request.

#
ProtocolResponse::new

fn ProtocolResponse::new(status~ : Int, headers? : Array[HttpHeader], body? : Bytes) -> ProtocolResponse

#
Rect

pub(all) struct Rect {
x : Int
y : Int
width : Int
height : Int
} derive(Eq,
Debug
)

A pixel rectangle relative to the caller-owned native parent container.

#
Rect::new

fn Rect::new(x~ : Int, y~ : Int, width~ : Int, height~ : Int) -> Rect

#
WebContext

pub(all) struct WebContext {
// private fields
} derive(Eq,
Debug
)

A browser-data context that can be shared by multiple WebViews.

#
WebContext::ephemeral

fn WebContext::ephemeral() -> WebContext

Creates an isolated, non-persistent context.

This is supported by WKWebView and WebKitGTK. WebView2 currently rejects this mode because it does not expose a compatible cross-platform profile.

#
WebContext::persistent

fn WebContext::persistent(data_directory? : String) -> WebContext

Creates a persistent context. A non-empty data_directory is supported on Windows and Linux; macOS rejects it rather than silently using another path.

#
WebContextStorage

pub(all) enum WebContextStorage {
Persistent
Ephemeral
} derive(Eq,
Debug
)

The persistence policy for browser data owned by a WebContext.

#
WebView

pub struct WebView {
// private fields
}

An embedded platform WebView associated with a caller-owned native container.

#
WebView::add_init_script

fn WebView::add_init_script(self : WebView, script : String) -> Result[Unit, WebViewError]

#
WebView::attach_ohos

fn WebView::attach_ohos(web_tag : String, options : OhosAttachOptions) -> Result[WebView, WebViewError]

Attaches Moonview to an ArkUI-owned OpenHarmony Web component.

Call this on the ArkUI UI thread after the host has created the component with the same stable web_tag. The host remains responsible for its source, layout, visibility, and permission policy. The API is experimental and currently supports only reload, fire-and-forget eval, and destroy.

#
WebView::create

fn WebView::create(parent_handle : UInt64, options : WebViewOptions) -> Result[WebView, WebViewError]

Starts asynchronous creation of a WebView child view in parent_handle.

The caller must keep the native parent container alive and run its UI event loop until the listener receives WebViewEvent::Ready or CreationFailed. A later ProcessFailed is terminal: destroy the view and create a new one explicitly after the host has handled the failure. On Windows, this is an HWND; on macOS, an NSView*; and on Linux, a GtkFixed*. Every later command, including destroy, must use this same UI thread.

#
WebView::create_in_context

fn WebView::create_in_context(context : WebContext, parent_handle : UInt64, options : WebViewOptions) -> Result[WebView, WebViewError]

Starts asynchronous creation in a browser-data context shared by one or more WebViews.

#
WebView::destroy

fn WebView::destroy(self : WebView) -> Result[Unit, WebViewError]

Destroys the native child view. Repeated calls are harmless.

#
WebView::eval

fn WebView::eval(self : WebView, script : String, request_id : String) -> Result[Unit, WebViewError]

#
WebView::focus

fn WebView::focus(self : WebView) -> Result[Unit, WebViewError]

#
WebView::go_back

fn WebView::go_back(self : WebView) -> Result[Unit, WebViewError]

#
WebView::go_forward

fn WebView::go_forward(self : WebView) -> Result[Unit, WebViewError]

#
WebView::lifecycle

fn WebView::lifecycle(self : WebView) -> WebViewLifecycle

#
WebView::load_html

fn WebView::load_html(self : WebView, html : String) -> Result[Unit, WebViewError]

#
WebView::navigate

fn WebView::navigate(self : WebView, url : String) -> Result[Unit, WebViewError]

#
WebView::navigation_state

fn WebView::navigation_state(self : WebView) -> NavigationState

Returns the last document URL and history state reported by the native backend. The value is updated asynchronously through navigation events.

#
WebView::open_devtools

fn WebView::open_devtools(self : WebView) -> Result[Unit, WebViewError]

Opens the platform developer tools for this WebView.

This is supported by the Windows and Linux backends. macOS does not expose a supported public API for programmatically opening WKWebView inspector.

#
WebView::open_print_dialog

fn WebView::open_print_dialog(self : WebView) -> Result[Unit, WebViewError]

Opens the platform print dialog for the current document.

The dialog is available after Ready. Older WebView2 runtimes and macOS releases before 11 return Unsupported.

#
WebView::post_message

fn WebView::post_message(self : WebView, message : String) -> Result[Unit, WebViewError]

Posts an application-defined UTF-8 message to window.moonview in the page.

#
WebView::reload

fn WebView::reload(self : WebView) -> Result[Unit, WebViewError]

#
WebView::respond_protocol

fn WebView::respond_protocol(self : WebView, request_id : String, response : ProtocolResponse) -> Result[Unit, WebViewError]

Completes a pending custom-scheme request. The request ID is valid only until the native backend's 30-second response deadline expires.

#
WebView::set_bounds

fn WebView::set_bounds(self : WebView, bounds : Rect) -> Result[Unit, WebViewError]

#
WebView::set_visible

fn WebView::set_visible(self : WebView, visible : Bool) -> Result[Unit, WebViewError]

#
WebView::set_zoom_factor

fn WebView::set_zoom_factor(self : WebView, factor : Double) -> Result[Unit, WebViewError]

Sets the page zoom factor. Values must be greater than zero.

#
WebView::show_file_dialog

fn WebView::show_file_dialog(self : WebView, options : FileDialogOptions) -> Result[FileDialogResult, WebViewError]

Shows a native file dialog owned by this WebView's native container.

The method must run on the WebView creation thread. A user cancellation is returned as FileDialogResult::Cancelled; backend and native failures are returned as WebViewError values.

#
WebView::stop

fn WebView::stop(self : WebView) -> Result[Unit, WebViewError]

#
WebViewError

pub(all) enum WebViewError {
Unavailable
Unsupported(String)
ConfigurationLocked
CreateRejected
WrongThread
Destroyed
NativeFailure(Int, String)
} derive(Eq,
Debug
)

Failures reported before or during native WebView creation, after disposal, or when a command is issued outside the owner UI thread.

#
WebViewEvent

pub(all) enum WebViewEvent {
Ready
CreationFailed(WebViewError)
ProcessFailed(WebViewError)
PageMessage(String)
NavigationStarting(String)
SourceChanged(String)
NavigationCompleted(String)
NavigationFailed(String, WebViewError)
TitleChanged(String)
HistoryChanged(Bool, Bool)
ScriptResult(String, String)
ScriptFailed(String, WebViewError)
ProtocolRequest(ProtocolRequest)
ProtocolCancelled(String)
} derive(Eq,
Debug
)

Events emitted on the native UI thread that owns the parent container.

ScriptResult and ScriptFailed preserve the request identifier supplied to WebView::eval. ScriptResult is JSON text; an undefined JavaScript result is represented as null. Page messages are UTF-8 strings without an imposed protocol.

#
WebViewLifecycle

pub(all) enum WebViewLifecycle {
Creating
Ready
Failed(WebViewError)
Destroyed
} derive(Eq,
Debug
)

State reported by an asynchronously-created native WebView.

#
WebViewOptions

pub(all) struct WebViewOptions {
context : WebContext
bounds : Rect
resource_limits : WebViewResourceLimits
initial_url : String
initial_html : String
initialization_script : String
user_agent : String
visible : Bool
on_event : (WebViewEvent) -> Unit
on_navigation : (String) -> NavigationDecision
on_new_window : (String) -> NewWindowDecision
on_media_permission : (MediaPermissionRequest) -> MediaPermissionDecision
}

Configuration passed while the native WebView is being created.

If both initial content fields are non-empty, initial_html takes precedence. Treat the WebView as usable only after its Ready event.

#
WebViewOptions::new

fn WebViewOptions::new(bounds~ : Rect, context? : WebContext, resource_limits? : WebViewResourceLimits, initial_url? : String, initial_html? : String, initialization_script? : String, user_agent? : String, visible? : Bool, on_event? : (WebViewEvent) -> Unit, on_navigation? : (String) -> NavigationDecision, on_new_window? : (String) -> NewWindowDecision, on_media_permission? : (MediaPermissionRequest) -> MediaPermissionDecision) -> WebViewOptions

#
WebViewResourceLimits

pub(all) struct WebViewResourceLimits {
max_pending_commands : Int
max_pending_command_bytes : Int
max_protocol_request_body_bytes : Int
} derive(Eq,
Debug
)

Per-WebView resource limits enforced by the desktop native backends.

A value of 0 disables the corresponding limit. Negative values are rejected by WebView::create.

#
WebViewResourceLimits::new

fn WebViewResourceLimits::new(max_pending_commands? : Int, max_pending_command_bytes? : Int, max_protocol_request_body_bytes? : Int) -> WebViewResourceLimits

#
available

fn available() -> Bool

Returns whether the native backend is available on the current host.

#
register_custom_scheme

fn register_custom_scheme(name : String) -> Result[Unit, WebViewError]

Registers an application-owned custom URL scheme for the process.

Call this before the first successful WebView::create. Native handlers have a 30-second response deadline; unanswered requests are cancelled by the backend and reported as ProtocolCancelled.

Powered by MoonBit

Site sourceReport issuePackagesBuild queueSkillsStatistics

© 2026 mooncakes.io