Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 104 ยท Building a Real UI

WebView and Search Bars

Embed web content with WebView in Jetpack Compose, handle navigation, back presses and the JavaScript bridge safely, and add Material 3 SearchBar or SearchView for search.

Two small widgets show up in almost every real app and are rarely taught well: the WebView, which shows web content inside your screen (a privacy policy, a help center, a payment page, an article), and the search bar, which filters or looks things up as the user types. Both look simple. Both have traps: a WebView that loads untrusted pages can hurt your users, and a search box that queries on every keystroke can hammer your server and flicker the UI.

This lesson covers the WebView inside Compose, its two client classes, back handling, JavaScript and the bridge, and when to use Custom Tabs instead. Then it covers the Material 3 SearchBar and DockedSearchBar and the older SearchView. Android classes cannot run on the site, so the real code is read-only; the TryIts are plain Kotlin stand-ins that model URL policy, WebView history and debounced search, the three ideas worth practicing.

A WebView runs a full browser engine inside your app. Read Android security alongside this lesson, especially the WebView section. The short version: load only content you trust, keep JavaScript off unless you need it, and never expose a bridge to pages you do not control.

Should it be a WebView at all?

Before writing any code, choose the right tool:

  • Custom Tabs (CustomTabsIntent, from androidx.browser) open a page in the user's browser, inside your app's flow, with the browser's cookies, saved logins, password manager and security. Use them for "open this link", sign-in pages and external sites. They are the default answer for third-party content.
  • WebView is for content that must look like part of your app: your own help pages, a rich-text article, an embedded checkout, a hybrid screen. You control the page, so you can control the bridge.
  • Native UI is the answer when the "page" is really data. Parse the JSON and render it with Compose.

WebView in Compose

Compose has no WebView composable in Material 3, so you host the View with AndroidView (see Views interop). You need the INTERNET permission in the manifest (see permissions) for remote pages.

Kotlin
// read-only example: a minimal WebView screen
@Composable
fun HelpPage(url: String, modifier: Modifier = Modifier) {
    var webView by remember { mutableStateOf<WebView?>(null) }
    var canGoBack by remember { mutableStateOf(false) }
    var progress by remember { mutableIntStateOf(0) }

    BackHandler(enabled = canGoBack) { webView?.goBack() }

    Column(modifier) {
        if (progress in 1..99) {
            LinearProgressIndicator(progress = { progress / 100f }, modifier = Modifier.fillMaxWidth())
        }
        AndroidView(
            modifier = Modifier.fillMaxSize(),
            factory = { context ->
                WebView(context).apply {
                    settings.javaScriptEnabled = false          // enable only if the page needs it
                    settings.allowFileAccess = false
                    webViewClient = object : WebViewClient() {
                        override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) {
                            canGoBack = view.canGoBack()
                        }
                    }
                    webChromeClient = object : WebChromeClient() {
                        override fun onProgressChanged(view: WebView, newProgress: Int) {
                            progress = newProgress
                        }
                    }
                    loadUrl(url)
                    webView = this
                }
            },
            update = { /* state flowing in; avoid reloading on every recomposition */ },
            onRelease = { it.destroy() },
        )
    }
}

Three details deserve attention:

  1. factory runs once. Create and configure the WebView there. update runs on every recomposition, so calling loadUrl there would reload the page constantly. Load only when the target URL actually changes, for example by comparing with view.url.
  2. Release the WebView. onRelease calls destroy() so the engine's memory is freed when the composable leaves the screen.
  3. Lifecycle. For long-lived pages call onPause() and onResume() from a LifecycleEventObserver (see lifecycle) so media and timers stop in the background.

Google's accompanist-webview library and newer Compose WebView wrappers exist, but they have changed or been deprecated over time; wrapping the View yourself, as above, is stable and short.

WebViewClient and WebChromeClient

Two helper classes receive what the page does. The split is easy to remember: client = navigation and loading, chrome client = browser UI.

Class Typical callbacks
WebViewClient shouldOverrideUrlLoading (decide whether to follow a link), onPageStarted, onPageFinished, onReceivedError, shouldInterceptRequest (serve local files for URLs), doUpdateVisitedHistory
WebChromeClient onProgressChanged, onReceivedTitle, onShowFileChooser (file uploads), onPermissionRequest (camera for the page), onJsAlert, onShowCustomView (fullscreen video)

shouldOverrideUrlLoading is your security gate: return true to cancel a navigation, false to let the WebView load it. A good policy follows only your own HTTPS host, and hands other links to the browser with an Intent (see intents). The first stand-in is that policy as a function you can test, which is also how you would test it in a unit test.

Kotlin A navigation policy for shouldOverrideUrlLoading (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the lookalike help.example.com.evil.test. Compare the parsed host exactly; never use startsWith("https://help.example.com") on the raw string, because attackers register hosts that begin with yours.

JavaScript and the bridge

JavaScript is off by default. Turn it on with settings.javaScriptEnabled = true only when the page needs it, and only for pages you trust. When your page must talk to the app, there are three mechanisms, from safest to riskiest:

  1. URL schemes or intercepted navigation: the page navigates to myapp://action; you catch it in shouldOverrideUrlLoading. Simple, one-directional.
  2. WebMessagePort / WebViewCompat.addWebMessageListener (from androidx.webkit): message passing that lets you restrict which origins may talk to the app. This is the recommended modern bridge.
  3. addJavascriptInterface: exposes a Kotlin object to every frame in the page. Only methods annotated @JavascriptInterface are callable, but a page or injected ad that can run script can call them all. Never use it with pages you do not fully control.
Kotlin
// read-only example: a bridge restricted to one origin with addWebMessageListener
if (WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {
    WebViewCompat.addWebMessageListener(
        webView,
        "AppBridge",                                   // name visible to the page's JavaScript
        setOf("https://help.example.com"),             // only this origin may use it
    ) { _, message, sourceOrigin, isMainFrame, replyProxy ->
        if (isMainFrame && message.data == "getAppVersion") {
            replyProxy.postMessage(BuildConfig.VERSION_NAME)
        }
    }
}

In the page, JavaScript calls AppBridge.postMessage("getAppVersion"). Treat every message as untrusted input: validate and whitelist actions, never eval or build SQL from it.

To run script from the app into the page, call webView.evaluateJavascript("document.title", callback). The callback receives the result as a JSON string on the main thread.

For your own bundled pages, avoid file:// URLs. WebViewAssetLoader (from androidx.webkit) serves files from assets/ on a fake HTTPS origin (https://appassets.androidplatform.net/assets/...), so same-origin rules apply and you can leave file access disabled; plug it into shouldInterceptRequest.

Back handling and history

A WebView keeps its own history. If the user presses Back inside a WebView screen, you want the page to go back first and the screen to close only when there is no page history. That is the BackHandler(enabled = canGoBack) in the example above (see back stack and deep links for the predictive back gesture and BackHandler). canGoBack changes after the page loads, so update it from doUpdateVisitedHistory as shown.

The second stand-in is a WebView-like history stack that applies the same rules, including the one that confuses people: navigating after going back discards the forward entries.

Kotlin WebView history and back handling (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Other practical points

  • Dark mode. The page does not follow your theme by itself. With androidx.webkit you can set WebSettingsCompat.setAlgorithmicDarkeningAllowed(settings, true), or ship a prefers-color-scheme aware stylesheet.
  • Errors. Show your own error UI from onReceivedError, and offer a retry. Remember offline users (see errors and offline-first).
  • Cookies and sign-in. WebView cookies are separate from the browser's. CookieManager lets you set them; never put long-lived tokens in URLs.
  • Performance. A WebView is heavy to create (it starts engine processes). Do not put many in a list; reuse one when possible.
  • Testing. Unit-test your URL policy (like the stand-in above); WebView content itself needs instrumented tests (see instrumented tests).

Search in Material 3

Search is the second half of this lesson. Material 3 offers two composables:

  • SearchBar is the expandable search: a pill-shaped field that expands into a full-screen search view that shows suggestions and results, with a back arrow. Use it on screens where search is a major feature.
  • DockedSearchBar is a search field with a dropdown panel under it, which suits tablets and desktop-like layouts (see adaptive layouts).

In current Material 3 releases, both use the same pattern: a SearchBarDefaults.InputField supplies the text field, and a lambda receives the expanded state. APIs have changed between releases (SearchBar once took query, onQueryChange and active directly), so check your version's documentation.

Kotlin
// read-only example: search with suggestions, state kept in a ViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotesSearch(viewModel: SearchViewModel = hiltViewModel()) {
    val query by viewModel.query.collectAsStateWithLifecycle()
    val results by viewModel.results.collectAsStateWithLifecycle()
    var expanded by rememberSaveable { mutableStateOf(false) }

    SearchBar(
        inputField = {
            SearchBarDefaults.InputField(
                query = query,
                onQueryChange = viewModel::onQueryChange,
                onSearch = { expanded = false },
                expanded = expanded,
                onExpandedChange = { expanded = it },
                placeholder = { Text("Search notes") },
                leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) },
            )
        },
        expanded = expanded,
        onExpandedChange = { expanded = it },
    ) {
        LazyColumn {
            items(results, key = { it.id }) { note ->
                ListItem(
                    headlineContent = { Text(note.title) },
                    modifier = Modifier.clickable { expanded = false; viewModel.open(note) },
                )
            }
        }
    }
}

The query is state that belongs in a ViewModel (see ViewModel and StateFlow in Compose). The ViewModel turns keystrokes into results with Flow operators:

Kotlin
// read-only example
@OptIn(FlowPreview::class)
val results: StateFlow<List<Note>> = query
    .debounce(300)                       // wait until typing pauses
    .map { it.trim() }
    .distinctUntilChanged()
    .flatMapLatest { q -> if (q.isBlank()) flowOf(emptyList()) else repo.search(q) }
    .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

debounce avoids a query per keystroke, distinctUntilChanged skips repeats and flatMapLatest cancels the previous search when the user types again, so a slow old answer can never overwrite a newer one. For local data, search can run directly in Room with a LIKE query (see Room basics).

Kotlin Debounce and flatMapLatest-style search (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

SearchView in the View system

In XML layouts the equivalent is androidx.appcompat.widget.SearchView, often placed in the app bar through a menu item with app:actionViewClass="androidx.appcompat.widget.SearchView" (menus are covered in menus and dialogs). You attach a OnQueryTextListener with onQueryTextChange(newText) and onQueryTextSubmit(query), and feed results to a RecyclerView adapter (see RecyclerView). Use the same debounce idea (a Handler delay or a Flow created with callbackFlow). The Android framework SearchView also exists, but the AppCompat one is the standard.

Beyond in-app lists, Android can also offer system search integration: app shortcuts, and SearchRecentSuggestions for remembering past queries. Most apps need neither; keep your search simple and fast.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In AndroidView, where should you create and configure the WebView?

    factory builds the View once. Calling loadUrl in update would reload the page on every recomposition.
  2. 2. What does returning true from shouldOverrideUrlLoading mean?

    True means the host app took over; the WebView does not load the URL. Return false to let it load.
  3. 3. Which JavaScript bridge approach lets you restrict which origins may talk to your app?

    addWebMessageListener takes a set of allowed origin rules. addJavascriptInterface exposes the object to every page and frame loaded in the WebView.
  4. 4. A user types 'mil', pauses, and the search runs. They keep typing 'mile' while the first search is still running. What does flatMapLatest do?

    flatMapLatest cancels the previous inner flow when a new value arrives, so stale results cannot replace newer ones.
  5. 5. When is a Custom Tab a better choice than a WebView?

    Custom Tabs run in the user's browser with its saved logins and protections. Use WebView only for content you control and need inside your UI.

Summary

  • Prefer Custom Tabs for external pages; use WebView for content you control or must integrate.
  • Host a WebView in Compose with AndroidView: configure in factory, release in onRelease, never loadUrl unconditionally in update.
  • WebViewClient handles navigation (your URL allowlist lives in shouldOverrideUrlLoading); WebChromeClient handles progress, titles and permissions.
  • Keep JavaScript off by default; prefer addWebMessageListener with origin limits over addJavascriptInterface; serve local pages with WebViewAssetLoader.
  • Wire BackHandler(enabled = canGoBack) so Back moves through page history first.
  • Use Material 3 SearchBar or DockedSearchBar with the query in a ViewModel and debounce + distinctUntilChanged + flatMapLatest; SearchView is the Views equivalent.

Next: Views Interop and Legacy XML