DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Akira Kashihara
Akira Kashihara

Posted on

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.

Top comments (0)

๐ŸŒš Friends don't let friends browse without dark mode.

Sorry, it's true.