Compose WebView Part 11 | Webpage not available
Error Screen: When the web page is not available means, you can show error message on app screen “404 page not found” or any type of error message related to the problem, instead of showing broken web page like Webpage not available.
This example demonstrates how do I load 404 files from asset directory into WebView in android.
Ref this link to load assets files : https://www.boltuix.com/2022/07/compose-webview-part-4-offline.html
In our main activity, we are going to use web client object's onReceivedError override method to handle web errors in our web view application
package com.blogspot.boltuix
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import android.webkit.*
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.*
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.viewinterop.AndroidView
//invalid url
var loadURL = "https://www.boltuix1.com/"
// valid url
//var loadURL = "https://www.boltuix1.com/"
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WebViewPage(loadURL)
}
}
}
@OptIn(ExperimentalComposeUiApi::class)
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun WebViewPage(url: String){
val mutableStateTrigger = remember { mutableStateOf(false) }
AndroidView(
factory = {
WebView(it).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
webViewClient = WebViewClient()
// to play video on a web view
settings.javaScriptEnabled = true
webViewClient = object : WebViewClient() {
override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
super.onReceivedError(view, request, error)
loadURL = "file:///android_asset/404.html"
mutableStateTrigger.value = true
}
}
loadUrl(url)
}
}, update = {
it.loadUrl(url)
})
if (mutableStateTrigger.value) {
WebViewPage(loadURL)
}
}
..
GET full source code on Github:
https://github.com/BoltUIX/Compose-Web-View
Comments
Post a Comment