Skip to content

About

Cross-platform native WebView integration for HuxerUI.

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

HuxerUI WebView

HuxerUI WebView is a portable embedded web-content component for HuxerUI applications. It provides a common C++ API for navigation, custom requests, HTML content, JavaScript evaluation, page-to-application messaging, and observable browser state.

The library uses the platform web engine and integrates it as a HuxerUI PlatformView.

Preview

Windows
HuxerUI WebView preview on Windows
macOS
HuxerUI WebView preview on macOS
Android iOS
HuxerUI WebView preview on Android HuxerUI WebView preview on iOS

Features

  • Declarative URL and JavaScript configuration
  • Retained controller for browser commands
  • Back, forward, reload, and stop operations
  • URL, request, and inline HTML loading
  • Navigation policy and lifecycle events
  • Page title, progress, loading, and history state
  • JavaScript evaluation with asynchronous results
  • Text messages from page JavaScript through huxerui.postMessage

Supported platforms

Platform Engine Notes
Android Android WebView Android API 23 or later
iOS WKWebView iOS 15 or later
Linux WebKitGTK WebKitGTK 6.0 (2.40 or later); requires HuxerUI 0.5.0 or later
macOS WKWebView WebKit is linked by the library
Windows WebView2 Downloads the WebView2 SDK when building and requires the WebView2 Runtime when running
Web iframe Subject to browser embedding and cross-origin restrictions

Add the library

The library requires CMake 3.20 or later and a configured HuxerUI SDK.

Add the Git repository after the application's huxerui_add_app call:

huxerui_use_library(my_app
        TARGET HuxerUI::WebView
        URL "https://github.com/HuxerUI/Lib-WebView.git"
        TAG "v0.1.0"
)

Include the public API with:

#include <huxerui/webview.h>

On Windows, the first configure downloads the pinned Microsoft WebView2 SDK. Set WEBVIEW2_SDK_ROOT to an extracted Microsoft WebView2 NuGet package root to use a local SDK, including for offline builds.

Quick start

Install the platform adapter in the application root, retain a controller in composition, and keep navigation output in application state:

#include <huxerui/huxerui.h>
#include <huxerui/webview.h>

using namespace huxerui;

[[huxerui::composable]]
View WebContent() {
  auto requested_url = UseState(std::string("https://example.com"));
  auto navigation = UseState(WebViewNavigationState{
      .url = requested_url,
  });
  WebViewController controller = UseWebViewController();

  return Column {
    Row {
      Button("Back")
          .OnClick([controller] {
            controller.GoBack();
          })
          .With(Enabled(navigation->can_go_back)),
      Button("Forward")
          .OnClick([controller] {
            controller.GoForward();
          })
          .With(Enabled(navigation->can_go_forward)),
      Button("Reload").OnClick([controller] {
        controller.Reload();
      }),
      Button("Documentation").OnClick([controller] {
        controller.LoadUrl("https://github.com/HuxerUI/HuxerUI");
      }),
    }.With(Spacing(8.0F)),
    WebView({
          .url = requested_url,
          .java_script_enabled = false,
        }, controller)
        .On<WebViewEvents::NavigationChanged>(
            [requested_url, navigation](const WebViewNavigationState& state) {
              requested_url = state.url;
              navigation = state;
            }
        )
        .With(Grow(), Frame{.min_height = 320.0F}, ClipChildren()),
  }.With(Spacing(8.0F), CrossAlign(CrossAxisAlignment::Stretch));
}

View App() {
  return FlatTheme(WebContent());
}

const Application application{
    App,
    {
        .application_hooks = {
            huxerui::InstallWebView,
        },
    }
};

WebView is a PlatformView leaf and has no portable intrinsic size. Give it bounded geometry with Grow, Frame, or another bounded parent layout.

Navigation model

WebViewProperties::url is controlled application state. Changing it starts a top-level navigation when the value is different from the current property value. Write WebViewNavigationState::url back to the same state when links, redirects, or browser history should become the new controlled value.

Use LoadUrl as a convenient imperative GET entry point:

controller.LoadUrl("https://example.com/account");

Use LoadRequest when a request needs a method, headers, or body:

controller.LoadRequest({
    .url = "https://example.com/session",
    .method = "POST",
    .headers = {{"Content-Type", "application/json"}},
    .body = R"({"remember":true})",
});

Custom request capabilities depend on the platform engine. The Web target accepts only GET navigation without custom headers or a body.

Load content directly with an optional base URL:

controller.LoadHtml({
    .content = "<h1>Hello from HuxerUI</h1>",
    .base_url = "https://example.com/",
});

Controller commands return false when the controller is not connected or the active platform cannot accept the operation. A true result means the command was accepted, not that navigation or evaluation completed.

Color scheme

Set theme_brightness to request light or dark web content. The default std::nullopt follows the host environment:

WebView({
    .url = requested_url,
    .theme_brightness = ThemeBrightness::Dark,
}, controller)

Windows, iOS, and macOS apply this preference before the initial navigation and when the property changes, including the prefers-color-scheme media query. Restoring std::nullopt returns to the system preference. On Windows, the override is scoped to each WebView2 instance and does not change shared Profile preferences.

Android WebView follows the host application's isLightTheme, and Linux WebKitGTK follows the host environment; explicit per-view Light and Dark overrides are unsupported. Web uses iframe color-scheme propagation, so behavior depends on browser support and the embedded page's own color-scheme support. Cross-origin preference propagation does not grant DOM or script access, and normal iframe embedding policies still apply.

This is a preference, not algorithmic darkening: the library does not force-invert content or rewrite site CSS.

Events

Events are attached to the WebView declaration with .On<Event>(handler).

Event Purpose
WebViewEvents::NavigationRequested Synchronously allow or cancel a pending navigation
WebViewEvents::NavigationChanged Receive the latest URL, title, loading, progress, and history snapshot
WebViewEvents::LoadStarted Observe the start of a top-level load
WebViewEvents::LoadFinished Observe successful completion
WebViewEvents::LoadFailed Receive a platform diagnostic code, message, and optional URL
WebViewEvents::MessageReceived Receive text posted by page JavaScript

Return false from NavigationRequested to cancel a request. The decision is synchronous; do not start asynchronous policy work from the handler.

.On<WebViewEvents::NavigationRequested>([](const WebViewNavigationRequest& request) {
  return !request.is_main_frame || IsAllowedNavigation(request.url);
})

In this example, IsAllowedNavigation is an application-defined policy that validates the complete URL.

Browser-hosted cross-origin pages may expose approximate navigation state. Unavailable titles are empty and unavailable history actions are false.

JavaScript

JavaScript is disabled by default. Enable it in the complete property snapshot when the loaded content requires it:

WebView({
    .url = requested_url,
    .java_script_enabled = true,
}, controller)

Evaluate a script through the controller and inspect the PlatformResult in the completion callback:

controller.EvaluateJavaScript(
    "({title: document.title, url: location.href})",
    [](PlatformResult<std::string> result) {
      if (const auto* value = std::get_if<std::string>(&result)) {
        // Use the platform's JSON representation in *value.
      } else {
        const PlatformError& error = std::get<PlatformError>(result);
        // Report error.message to the application.
      }
    }
);

When JavaScript is enabled, a page can send text to the application:

huxerui.postMessage("ready");

Receive it with:

.On<WebViewEvents::MessageReceived>([](const std::string& message) {
  // Treat message as untrusted input.
})

Security

  • Treat every URL, JavaScript result, and page message as untrusted input.
  • Restrict navigation to application-approved destinations when displaying external content.
  • Enable JavaScript only for content that needs it.
  • Do not place secrets in evaluated scripts or page messages.
  • Expect CSP, X-Frame-Options, sandboxing, CORS, and other browser policies to affect the Web target.

The message bridge does not make page content trusted. Validate message formats and enforce application authorization before performing privileged actions.

Linux backend

Linux integrates WebKitGTK through HuxerUI's GTK PlatformView host (HuxerUI 0.5.0 or later). CMake first looks for WebKitGTK 6.0 (version 2.40 or later) through pkg-config. If it is not installed, the build downloads WebKitGTK 2.54.2 from the official release archive, verifies its SHA-256, and builds and installs it under the build directory without administrator access. Installing the distribution's WebKitGTK development package avoids building the browser engine from source.

The source fallback requires Ninja and the WebKitGTK build dependencies, including the system GTK 4 and libsoup 3 development packages. See the upstream build instructions. Keep the generated installation with its libraries, helper processes, and resources available when running applications that use the downloaded engine.

The backend supports URL and HTML loading, GET requests with custom headers, JavaScript evaluation, navigation events, platform cookie management through WebKitCookieManager, and the window.huxerui.postMessage bridge. WebKitGTK does not expose setters for a navigation request's method or body, so non-GET requests and request bodies emit a load error.

DMABUF rendering is disabled by default for compatibility with the host renderer; an explicitly set WEBKIT_DISABLE_DMABUF_RENDERER value takes precedence.

Preview application

The preview under examples/preview provides a browser-style interface and demonstrates navigation, custom requests, inline HTML, JavaScript evaluation, and page messages.

Build and run it with the HuxerUI CLI from the preview directory:

cd examples/preview
huxerui build macos --profile debug
huxerui run macos --profile debug

Replace macos with another supported platform configured on the host.

API reference

The complete public contract and user-facing API comments are available in include/huxerui/webview.h.

Platform cookie access

controller.GetCookies(url, completion) reads the engine's cookie store for a specific URL, including HttpOnly cookies, and returns a Cookie request-header value. Treat this value as a credential: do not log it or expose it to page JavaScript. Supported by Android CookieManager, WKHTTPCookieStore on iOS/macOS, WebView2 CookieManager on Windows, and WebKitCookieManager on Linux. Web completes with webview/unsupported-cookies; iframe script access cannot expose HttpOnly cookies.

controller.SetCookie(url, cookie, completion) creates or updates a platform cookie. WebViewCookie supports Domain, Path, Expires, Secure, HttpOnly, and SameSite attributes. An absent expiration creates a session cookie; SameSite::None requires Secure. Successful writes complete with an empty string.

controller.DeleteCookie(url, name, domain, path, completion) deletes the cookie identified by its name, domain, and path. Deletion is idempotent and completes with an empty string.

controller.GetCookieList(url, completion) returns structured cookies, including their attributes, through PlatformResult<std::vector<WebViewCookie>>. It is supported on iOS/macOS, Windows, and Linux. Android CookieManager exposes only request-header values, so Android completes with webview/unsupported-cookie-details instead of inventing unavailable attributes. All three new operations complete with webview/unsupported-cookies on Web.

controller.ClearCookies(completion) deletes all cookies in the default data store, potentially affecting other WebViews using the same profile. It completes with an empty string. It does not delete localStorage or the HTTP cache.

All cookie commands require a mounted controller. As with other controller commands, false means the command was not accepted; true is not a success result. Applications must verify the imported session with their own server before committing login. Navigating to a callback URL is only a trigger, never proof of successful authentication.

Controller contract tests can be enabled with -DWEBVIEW_BUILD_TESTS=ON.

License

HuxerUI WebView is available under the MIT License.

About

Cross-platform native WebView integration for HuxerUI.

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages