Compose WebView Part 2 Play Video | Enable JS setting

JavaScript is disabled in a WebView by default. You can enable it through the WebSettings attached to your WebView.You can retrieve WebSettings with getSettings(), then enable JavaScript with setJavaScriptEnabled().

WebView With Jetpack Compose in Android Studio | Kotlin | Jetpack Compose | Android Tutorials

Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

package com.blogspot.boltuix

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.compose.ui.viewinterop.AndroidView

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            WebViewPage("https://www.boltuix.com/")
        }
    }
}
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun WebViewPage(url: String){

    // Adding a WebView inside AndroidView with layout as full screen
    AndroidView(factory = {

        WebView(it).apply {

            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )

            webViewClient = WebViewClient()

            // to enable JS
            settings.javaScriptEnabled = true

            // to verify that the client requesting your web page is actually your Android app.
            settings.userAgentString = System.getProperty("http.agent") //Dalvik/2.1.0 (Linux; U; Android 11; M2012K11I Build/RKQ1.201112.002)


            loadUrl(url)
        }
    }, update = {
        it.loadUrl(url)
    })
}


..

WebSettings provides access to a variety of other settings that you might find useful. 


For example, if you're developing a web application that's designed specifically for the WebView in your Android app, then you can define a custom user agent string with setUserAgentString(), then query the custom user agent in your web page to verify that the client requesting your web page is actually your Android app.

..

GET source code on Github:

Comments