WebView

The library shows web pages in a Compose Multiplatform application on the Aurora OS Chromium Embedded Framework (CEF) engine, without Qt. Pages are rendered offscreen and drawn in the Compose render pass; the application talks to page scripts over a Promise-based JavaScript bridge.

Permissions

Recommended set:

Permissions=Internet;UserDirs;DeviceInfo
Permission Level Used for
Internet Required Loading pages from the network
DeviceInfo Required Recognizing the emulator with RenderingMode.Auto to choose software or GPU rendering
UserDirs Recommended Saving downloads to the user's Downloads folder (PageRequest.Download.save()), choosing user files for pages (PageRequest.FileChooser)
Location Optional Device positions for navigator.geolocation
Camera Optional Camera capture of pages (PageRequest.MediaAccess with video)
Microphone Optional Microphone capture of pages (PageRequest.MediaAccess with audio)
ScreenCapture Optional Screen capture of pages (PageRequest.ScreenCapture)

Add optional permissions only if the application lets pages use these features.

Dependency libraries

  • cef (from 3rd_party/cef of aurora-maven, bundled into the application rpm)
  • EGL
  • ak-window, ak-path-info, ak-uri-launcher, ak-location-info

Features

Engine and rendering

  • Engine started by a Compose background renderer, after the first frame or with the first page.
  • GPU rendering in the main window's OpenGL ES context on devices, software on the emulator.
  • Viewport size and density, safe-area insets, orientation.
  • Active, hidden and frozen views, audio muting, memory pressure, renderer termination.

Navigation and content

  • Load URLs (with headers or as POST) and HTML (with base URL and MIME type).
  • Back/forward, reload/stop, URL, title, loading progress and errors.
  • Navigation filter for every navigation of the page and its frames.
  • Local content: virtual HTTPS hosts serving the application's directories.
  • Request interception: let through, block or answer requests by URL patterns.
  • Popup windows bound to their opener.
  • Links of other schemes (tel:, mailto:) handed to the system.

Scripts

  • JavaScript bridge: aurora.postMessage/aurora.invoke/aurora.onMessage with origin checks.
  • evaluateJavaScript with Promise results.
  • User scripts at the start of every document.

Page requests and input

  • alert/confirm/prompt, leave-page confirmation, permissions, camera/microphone access, file chooser, form resubmission.
  • Touch, keys, wheel, on-screen keyboard state and text composition.
  • Text selection with handles, clipboard commands, context menus.
  • Find in page, saving as PDF, snapshots.
  • Favicons, media playback and capture state, autoplay policy.
  • Downloads with progress, pause, resume and cancel.

Stores and security

  • Shared, named persistent and in-memory stores.
  • Cookies, browsing data, proxy, URL policy, site permissions, color scheme per store.
  • Geolocation for navigator.geolocation.
  • HTTP and proxy authentication, client certificates, certificate errors, connection security (GOST included, also through CryptoPro CSP).

Settings and diagnostics

  • JavaScript on/off, transparent background, page zoom, file:// access, pinch zoom.
  • Failed resource loads, HTTP errors, console messages.
  • Aurora User-Agent and client hints, mobile or desktop sites, custom User-Agent.

Example

val view = AuroraWebView(
    settings = WebViewSettings(
        javaScriptEnabled = true,
        userScripts = listOf(UserScript("window.appVersion = '1.2'")),
    ),
)

// Navigation
view.loadUrl("https://example.com")
view.loadUrl("https://example.com/account", mapOf("Authorization" to "Bearer $token"))
view.postUrl("https://example.com/login", "user=alice".encodeToByteArray())
view.loadHtml("<img src='logo.png'>", baseUrl = "https://example.com/app/")
view.goBack(); view.goForward(); view.reload(); view.stop()
view.setNavigationFilter { request -> !request.isMainFrame || !request.url.startsWith("tel:") }
view.url.collect { url -> }
view.loadUrl("https://appassets.internal/index.html")

// Page requests: every request must be answered once
view.requests.collect { request ->
    when (request) {
        is PageRequest.Alert -> request.ok()
        is PageRequest.Permission -> request.grant(remember = true)
        is PageRequest.FileChooser -> request.select(listOf("/home/defaultuser/Pictures/a.png"))
        is PageRequest.NewWindow -> request.open()
        is PageRequest.Download -> request.save()
        is PageRequest.HttpAuth -> request.authenticate("user", "password")
        is PageRequest.ClientCertificate -> request.continueWithout()
        else -> request.dismiss()
    }
}

// JavaScript bridge
view.handle("sum") { call ->
    val a = call.data.jsonObject.getValue("a").jsonPrimitive.int
    val b = call.data.jsonObject.getValue("b").jsonPrimitive.int
    InvokeResult.Resolved(JsonPrimitive(a + b))
}
view.messages("note").collect { message -> }
view.post("greeting", JsonPrimitive("Hello"))
when (val result = view.evaluateJavaScript("document.title")) {
    is ScriptResult.Success -> result.value
    is ScriptResult.Failure -> result.message
}

// Request interception
view.setRequestInterceptor(listOf(UrlPattern(OriginMatch.Only(listOf(OriginRule("https://*.ads.example")))))) { request ->
    if (request.resourceType == ResourceType.Image) InterceptResult.Block else InterceptResult.Allow
}

// Stores
val work = AuroraWebView(store = AuroraWebStore.profile("work"))
val privateView = AuroraWebView(store = AuroraWebStore.incognito())
AuroraWebStore.shared.cookies.set("https://example.com/", Cookie("token", "abc"))
AuroraWebStore.shared.browsingData.clearSite("https://example.com/")
AuroraWebStore.shared.proxy.set(ProxyConfig.Fixed(listOf(ProxyServer(ProxyScheme.Http, "proxy.corp", 3128))))
AuroraWebStore.shared.urlPolicy.set(UrlPolicy(blocklist = listOf("*"), allowlist = listOf("intranet.corp")))
AuroraWebStore.shared.permissions.set("https://meet.example", SitePermission.Camera, PermissionState.Granted)
AuroraWebStore.shared.colorScheme.set(ColorScheme.Dark)

// Page tools
view.find("receipt")
when (val pdf = view.saveAsPdf("${PathInfo.getDocuments()}/page.pdf", PdfSettings(landscape = true))) {
    is PdfResult.Saved -> pdf.path
    is PdfResult.Failed -> pdf.message
}
when (val snapshot = view.snapshot()) {
    is SnapshotResult.Captured -> snapshot.image
    is SnapshotResult.Unavailable -> snapshot.reason
}

// Text selection, keyboard and viewport
view.selection.collect { selection -> }
view.selectAll(); view.copy()
view.ime.collect { state -> }
view.setInsets(WebViewInsets(top = 80))

// Lifecycle, connection security and diagnostics
view.setActivity(WebViewActivity.Frozen)
AuroraWebEngine.memoryPressure.collect { pressure -> }
view.loading.collect { state ->
    if ((state as? LoadingState.Failed)?.error is LoadError.Certificate) view.proceedCertificateError()
}
view.resourceErrors.collect { error -> }
view.setUserAgent(UserAgent.BuiltIn(ContentMode.Desktop))

view.close()

Setup

Add the dependency and enable packaging of the engine runtime in build.gradle.kts:

kotlin {
    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation("ru.auroraos.kmp:ak-webview:0.0.1")
            }
        }
    }
}

auroraBuild {
    webview {
        enabled.set(true)
        locales.set(listOf("ru"))             // en-US is always packaged; default: en-US, ru
        softwareRenderingSupport.set(false)   // −25 MB; the emulator then cannot render pages
    }
}

Register the renderer in main(); only one AuroraWebViewRenderer may exist in a process:

fun main() = application(
    backgroundRenderers = listOf(AuroraWebViewRenderer()),
) {
    App()
}

Renderer parameters:

  • startup: when the engine starts, OnWindowReady (default) or Lazy (with the first page).
  • rendering: Auto (default), Gpu or Software.
  • remoteDebuggingPort: port of the DevTools server, off by default.
  • switches: extra engine command-line switches, e.g. --enable-logging.
  • fileUrlAccess: lets file:// pages read other files and reach any origin, off by default.
  • pinchZoom: two-finger zoom, on by default.
  • autoplay: when pages may start media with sound, UserGestureRequired by default.

AuroraWebEngine.lifecycle reports the engine state, e.g. Running(backend) or Failed(reason).

GOST TLS through CryptoPro

To open GOST sites on devices with CryptoPro CSP, build the application with the CryptoPro provider:

import ru.auroraos.kmp.build.plugin.configs.GostSSL

auroraBuild {
    webview {
        enabled.set(true)
        gostssl.set(GostSSL.CryptoPro)
    }
}

Local content

AuroraWebEngine.localContent serves directories of the application as virtual HTTPS hosts in every view and store, service workers included, without going to the network: https://<host>/<path> is answered with <directory>/<path>. Pages there have a secure origin with cookies, storage, modules and service workers, unlike file:// pages. Hosts can be changed from any thread at any time, also before the renderer exists; a change applies to loads started after the call returns.

fun main() {
    // Hosts known at start: add them before the renderer
    AuroraWebEngine.localContent.add(LocalContentHost("appassets.internal", "${PathInfo.getPackageFiles()}/www"))
    application(backgroundRenderers = listOf(AuroraWebViewRenderer())) { App() }
}

// Later: content unpacked or downloaded after start
AuroraWebEngine.localContent.add(LocalContentHost("bundle.internal", unpackedDirectory))
// A host of the same name gets the new directory (e.g. an updated bundle)
AuroraWebEngine.localContent.add(LocalContentHost("bundle.internal", updatedDirectory))
// Stop serving it
AuroraWebEngine.localContent.remove("bundle.internal")
AuroraWebEngine.localContent.hosts() // [LocalContentHost(appassets.internal, ...)]

Pages already loaded from a host keep their content and their Local connection security after it is removed or replaced, until they load another document. Service workers its pages registered are kept, like those of a site gone offline; a replaced directory updates them through the engine's regular update check of the worker script. To remove them, clear the site in each store that used the host: store.browsingData.clearSite("https://bundle.internal/").

Use a host name of your own, such as *.internal (reserved for private use): a real domain given as host replaces that site in all views, and its requests go to the real site again once removed.

JavaScript bridge

Every document of a view has the aurora object: aurora.postMessage(channel, data) and aurora.invoke(channel, data) reach the application, aurora.onMessage(channel, callback) receives what the application posts. Data is JSON. Every message and call comes with its sender (origin and frame) determined by the engine. By default only the main frame may use the bridge; setBridgeAccess(BridgeAccess(frames, origins)) allows other frames and limits origins.

Request interception

An interceptor lets the requests of a view that match UrlPatterns through, blocks them or answers them with InterceptResult.Respond(mimeType, body, headers), for ad blocking, offline caches and mock servers. A pattern has origin rules (https://*.example.com matches subdomains only) and a path with * wildcards; the query is ignored and data:, about:, file: URLs never match.