DEV Community

Akira Kashihara
Akira Kashihara

Posted on

6 3

How to Display a Web Application with Basic Authentication in WebView using Jetpack Compose (Android)

This article shows how to display a web application with Basic Authentication in WebView using Jetpack Compose.
The sample code on this article was made with reference to the thread on StackOverflow. StackOverflow's code is written in Java, but this article shows you the sample code in kotlin.

Source Code

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent{ MyWebClient(url = "https://hogehoge.hoge")}
    }
}

@SuppressLint("SetJavaScriptEnabled")
@Composable
fun MyWebClient(url: String) {

    AndroidView(factory = ::WebView,
    update = { webView ->
        webView.webViewClient = MyWebViewClient()
        webView.settings.javaScriptEnabled = true
        webView.loadUrl(url)

    })
}

// Ovverride onReceivedHttpAuthRequest in new class which extends WebViewClient().
private class MyWebViewClient: WebViewClient() {
    @Override
    override fun onReceivedHttpAuthRequest(
        view: WebView?,
        handler: HttpAuthHandler?,
        host: String?,
        realm: String?
    ) {
        if (handler != null) {
            handler.proceed("The user name to Basic Auth.", "The password to Basic Auth.")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

The Result

I cannot show you the contents of the web application. But I guess that you can check that all contents (text and images) are loaded.

The Preview of Execution


This original article is the following that is written by me. This is a translation of a portion of this original article from Japanese to English.

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs