Certainly! Let's enhance your Android app by implementing the following features:
-
Adding a Loading Indicator: Display a progress indicator while the WebView is loading a page.
-
Logging and Storing Cookies: Capture cookies from the WebView and store them using a persistent storage solution like SharedPreferences.
-
Modularizing the WebView: Move the WebView logic to a separate file, making it reusable for different websites with support for setting cookies and navigating between pages.
We'll break down the implementation into manageable steps:
- Create a Separate WebView Component
- Implement Loading Indicator
- Handle Cookie Logging and Storage
- Integrate the Modular WebView into MainActivity
Let's proceed step-by-step.
1. Create a Separate WebView Component
First, let's create a new Kotlin file for our modular WebView component. We'll call it CustomWebView.kt.
CustomWebView.kt
package com.example.osticket
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.Log
import android.view.ViewGroup
import android.webkit.*
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.edit
import java.util.*
@Composable
fun CustomWebView(
url: String,
modifier: Modifier = Modifier.fillMaxSize(),
onLoadingStateChanged: (Boolean) -> Unit = {},
onCookiesRetrieved: (String) -> Unit = {}
) {
var webView: WebView? by remember { mutableStateOf(null) }
var isLoading by remember { mutableStateOf(true) }
Box(modifier = modifier) {
AndroidView(
factory = { context ->
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
super.onPageStarted(view, url, favicon)
isLoading = true
onLoadingStateChanged(true)
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
isLoading = false
onLoadingStateChanged(false)
logAndStoreCookies(context, url)
}
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
super.onReceivedError(view, request, error)
Log.e("CustomWebView", "Error: ${error?.description}")
}
}
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
javaScriptCanOpenWindowsAutomatically = true
loadWithOverviewMode = true
allowContentAccess = true
allowFileAccess = true
builtInZoomControls = true
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
displayZoomControls = false
setSupportZoom(true)
defaultTextEncodingName = "utf-8"
}
webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
Log.d(
"CustomWebView",
"${consoleMessage?.message()} -- From line ${consoleMessage?.lineNumber()} of ${consoleMessage?.sourceId()}"
)
return true
}
}
// Inject cookies if any
setCookies(context)
loadUrl(url)
}.also { webView = it }
},
update = { view ->
// You can add dynamic updates here if needed
}
)
if (isLoading) {
CircularProgressIndicator(
modifier = Modifier
.fillMaxSize(),
color = MaterialTheme.colorScheme.primary
)
}
}
}
/**
* Logs cookies for the current URL and stores them in SharedPreferences.
*/
@SuppressLint("ApplySharedPref")
private fun logAndStoreCookies(context: Context, url: String?) {
url?.let {
val cookieManager = CookieManager.getInstance()
val cookies = cookieManager.getCookie(it)
Log.d("CustomWebView", "Cookies for $it: $cookies")
// Store cookies in SharedPreferences
context.getSharedPreferences("WEBVIEW_COOKIES", Context.MODE_PRIVATE).edit {
putString("cookies_$it", cookies)
}
}
}
/**
* Sets cookies from SharedPreferences if available.
*/
private fun WebView.setCookies(context: Context) {
val prefs = context.getSharedPreferences("WEBVIEW_COOKIES", Context.MODE_PRIVATE)
val existingCookies = prefs.all.filterKeys { it.startsWith("cookies_") }
existingCookies.forEach { entry ->
val url = entry.key.removePrefix("cookies_")
val cookies = entry.value as? String
cookies?.split(";")?.forEach { cookie ->
CookieManager.getInstance().setCookie(url, cookie)
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush()
}
}
Explanation:
2. Implement Loading Indicator
We've already integrated the loading indicator within the CustomWebView composable using a CircularProgressIndicator displayed over the WebView when isLoading is true.
However, to provide better control and visibility, you can manage the loading state in the parent composable. Let's update WebViewLayout accordingly.
3. Handle Cookie Logging and Storage
The CustomWebView handles logging and storing cookies in SharedPreferences. This ensures that cookies persist across sessions and can be reused when loading the WebView.
4. Integrate the Modular WebView into MainActivity
Now, let's update your MainActivity to utilize the new CustomWebView component with appropriate loading indicators and cookie management.
MainActivity.kt
package com.example.osticket
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import com.example.osticket.ui.theme.OsticketTheme
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
OsticketTheme {
Scaffold(
modifier = Modifier.fillMaxSize()
) { innerPadding ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
color = MaterialTheme.colorScheme.background
) {
var currentUrl by remember { mutableStateOf("http://digital-land.org/osticket/scp") }
var showLoading by remember { mutableStateOf(false) }
Column(modifier = Modifier.fillMaxSize()) {
if (showLoading) {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.height(4.dp),
color = MaterialTheme.colorScheme.primary,
trackColor = Color.Transparent
)
}
CustomWebView(
url = currentUrl,
onLoadingStateChanged = { isLoading ->
showLoading = isLoading
},
onCookiesRetrieved = { cookies ->
// Handle retrieved cookies if needed
// For example, you can update UI or perform other actions
},
modifier = Modifier.weight(1f)
)
}
}
}
}
}
}
}
Explanation:
5. Navigating Between Different Websites and Managing Cookies
To make the CustomWebView versatile for handling different websites, you can externalize the navigation and cookie management logic. Here's how you can achieve that:
a. Navigating to Another Page
Add functions to navigate the WebView externally. To do this, we'll use a WebView reference that's accessible outside the composable. We'll update the CustomWebView to expose navigation functions.
Update CustomWebView.kt
Modify the CustomWebView to accept a WebViewState:
package com.example.osticket
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.Log
import android.view.ViewGroup
import android.webkit.*
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.edit
import kotlin.collections.set
@Composable
fun CustomWebView(
state: WebViewState,
modifier: Modifier = Modifier.fillMaxSize(),
onLoadingStateChanged: (Boolean) -> Unit = {},
onCookiesRetrieved: (String) -> Unit = {}
) {
var webView: WebView? by remember { mutableStateOf(null) }
var isLoading by remember { mutableStateOf(true) }
Box(modifier = modifier) {
AndroidView(
factory = { context ->
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
super.onPageStarted(view, url, favicon)
isLoading = true
onLoadingStateChanged(true)
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
isLoading = false
onLoadingStateChanged(false)
logAndStoreCookies(context, url)
}
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
super.onReceivedError(view, request, error)
Log.e("CustomWebView", "Error: ${error?.description}")
}
}
settings.apply {
javaScriptEnabled = true
domStorageEnabled = true
javaScriptCanOpenWindowsAutomatically = true
loadWithOverviewMode = true
allowContentAccess = true
allowFileAccess = true
builtInZoomControls = true
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
displayZoomControls = false
setSupportZoom(true)
defaultTextEncodingName = "utf-8"
}
webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
Log.d(
"CustomWebView",
"${consoleMessage?.message()} -- From line ${consoleMessage?.lineNumber()} of ${consoleMessage?.sourceId()}"
)
return true
}
}
// Inject cookies if any
setCookies(context)
loadUrl(state.currentUrl)
}.also { webView = it }
},
update = { view ->
// Handle URL changes
if (state.shouldLoadUrl) {
view.loadUrl(state.newUrl)
state.onUrlLoaded()
}
// Handle navigation actions
state.navigationCommands.forEach { command ->
when (command) {
is WebViewNavigationCommand.NavigateForward -> view.goForward()
is WebViewNavigationCommand.NavigateBack -> view.goBack()
// Add more navigation commands as needed
}
}
state.clearNavigationCommands()
}
)
if (isLoading) {
CircularProgressIndicator(
modifier = Modifier
.fillMaxSize(),
color = MaterialTheme.colorScheme.primary
)
}
}
}
sealed class WebViewNavigationCommand {
object NavigateForward : WebViewNavigationCommand()
object NavigateBack : WebViewNavigationCommand()
// Add more commands if needed
}
class WebViewState {
var currentUrl by mutableStateOf("http://digital-land.org/osticket/scp")
var shouldLoadUrl by mutableStateOf(false)
var newUrl by mutableStateOf("")
var navigationCommands = mutableStateListOf<WebViewNavigationCommand>()
fun loadUrl(url: String) {
newUrl = url
shouldLoadUrl = true
}
fun navigateForward() {
navigationCommands.add(WebViewNavigationCommand.NavigateForward)
}
fun navigateBack() {
navigationCommands.add(WebViewNavigationCommand.NavigateBack)
}
fun onUrlLoaded() {
shouldLoadUrl = false
}
fun clearNavigationCommands() {
navigationCommands.clear()
}
}
Explanation:
-
WebViewState: Manages the state and provides methods to control navigation and URL loading.
-
Navigation Commands: Define sealed classes to represent different navigation actions (e.g., back, forward).
-
Composability: The WebView listens to state changes and executes appropriate actions (e.g., load a new URL, navigate back or forward).
b. Update MainActivity to Use WebViewState
Now, let's update MainActivity to utilize WebViewState for navigation and URL loading.
MainActivity.kt
package com.example.osticket
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import com.example.osticket.ui.theme.OsticketTheme
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
OsticketTheme {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Osticket WebView") },
actions = {
// Add navigation buttons if needed
}
)
},
modifier = Modifier.fillMaxSize()
) { innerPadding ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
color = MaterialTheme.colorScheme.background
) {
val webViewState = remember { WebViewState() }
var showLoading by remember { mutableStateOf(false) }
Column(modifier = Modifier.fillMaxSize()) {
if (showLoading) {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.height(4.dp),
color = MaterialTheme.colorScheme.primary,
trackColor = Color.Transparent
)
}
CustomWebView(
state = webViewState,
onLoadingStateChanged = { isLoading ->
showLoading = isLoading
},
onCookiesRetrieved = { cookies ->
// Handle retrieved cookies if needed
},
modifier = Modifier.weight(1f)
)
NavigationControls(webViewState)
}
}
}
}
}
}
}
@Composable
fun NavigationControls(state: WebViewState) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Button(
onClick = { state.navigateBack() },
enabled = true // You can add logic to enable/disable based on WebView's state
) {
Text("Back")
}
Button(
onClick = { state.navigateForward() },
enabled = true // You can add logic to enable/disable based on WebView's state
) {
Text("Forward")
}
// Add more buttons as needed (e.g., Refresh, Go to URL)
}
}
Explanation:
-
TopAppBar: Added a top bar with the app title.
-
WebViewState Instance: Created an instance of WebViewState to manage WebView interactions.
-
NavigationControls:
- A composable that provides UI buttons to navigate back and forward.
- You can expand this to include additional controls like refresh, stop loading, or input for new URLs.
-
Loading Indicator: A LinearProgressIndicator at the top updates visibility based on the loading state.
6. Usage Example: Navigating to a Different Website with Cookies
Suppose you want to navigate to a different website and set specific cookies. Here's how you can achieve this:
a. Update WebViewState to Handle Setting Cookies
Enhance WebViewState to include functionality for setting cookies.
Update WebViewState in CustomWebView.kt
class WebViewState(private val context: Context) {
var currentUrl by mutableStateOf("http://digital-land.org/osticket/scp")
var shouldLoadUrl by mutableStateOf(false)
var newUrl by mutableStateOf("")
var navigationCommands = mutableStateListOf<WebViewNavigationCommand>()
var cookiesToSet = mutableStateListOf<Pair<String, String>>() // Pair of URL and Cookie string
fun loadUrl(url: String) {
newUrl = url
shouldLoadUrl = true
}
fun navigateForward() {
navigationCommands.add(WebViewNavigationCommand.NavigateForward)
}
fun navigateBack() {
navigationCommands.add(WebViewNavigationCommand.NavigateBack)
}
fun setCookie(url: String, cookie: String) {
cookiesToSet.add(Pair(url, cookie))
}
fun onUrlLoaded() {
shouldLoadUrl = false
}
fun clearNavigationCommands() {
navigationCommands.clear()
}
fun clearCookiesToSet(): List<Pair<String, String>> {
val toSet = cookiesToSet.toList()
cookiesToSet.clear()
return toSet
}
}
b. Modify CustomWebView to Set Cookies
Adjust the CustomWebView to handle setting new cookies.
Update setCookies Function
@Composable
fun CustomWebView(
state: WebViewState,
// ... other parameters
) {
// ... existing code ...
AndroidView(
factory = { context ->
// ... existing WebView setup ...
WebView(context).apply {
// ... existing setup ...
// Set cookies from the state
setCookies(context, state)
loadUrl(state.currentUrl)
}.also { webView = it }
},
update = { view ->
// Handle URL changes
if (state.shouldLoadUrl) {
view.loadUrl(state.newUrl)
state.onUrlLoaded()
}
// Handle navigation actions
state.navigationCommands.forEach { command ->
when (command) {
is WebViewNavigationCommand.NavigateForward -> view.goForward()
is WebViewNavigationCommand.NavigateBack -> view.goBack()
}
}
state.clearNavigationCommands()
// Handle setting new cookies
state.clearCookiesToSet().forEach { (url, cookie) ->
CookieManager.getInstance().setCookie(url, cookie)
Log.d("CustomWebView", "Set cookie: $cookie for $url")
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush()
}
}
)
// ... existing UI code ...
}
@SuppressLint("ApplySharedPref")
private fun logAndStoreCookies(context: Context, url: String?) {
// ... existing code ...
}
private fun WebView.setCookies(context: Context, state: WebViewState) {
val prefs = context.getSharedPreferences("WEBVIEW_COOKIES", Context.MODE_PRIVATE)
val existingCookies = prefs.all.filterKeys { it.startsWith("cookies_") }
existingCookies.forEach { entry ->
val url = entry.key.removePrefix("cookies_")
val cookies = entry.value as? String
cookies?.split(";")?.forEach { cookie ->
CookieManager.getInstance().setCookie(url, cookie)
}
}
state.clearCookiesToSet().forEach { (url, cookie) ->
CookieManager.getInstance().setCookie(url, cookie)
Log.d("CustomWebView", "Set cookie: $cookie for $url")
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush()
}
}
Explanation:
-
Cookie Setting: The WebViewState now holds a list of cookies to set, which can be added via setCookie(url, cookie).
-
Setting New Cookies: During the update phase of AndroidView, the WebView sets new cookies as specified in the state.
c. Using the Enhanced WebViewState in MainActivity
Now, let's use the enhanced WebViewState to navigate to a different website and set cookies.
MainActivity.kt
@Composable
fun MainContent() {
val context = LocalContext.current
val webViewState = remember { WebViewState(context) }
var showLoading by remember { mutableStateOf(false) }
Column(modifier = Modifier.fillMaxSize()) {
if (showLoading) {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.height(4.dp),
color = MaterialTheme.colorScheme.primary,
trackColor = Color.Transparent
)
}
CustomWebView(
state = webViewState,
onLoadingStateChanged = { isLoading ->
showLoading = isLoading
},
onCookiesRetrieved = { cookies ->
// Handle retrieved cookies if needed
},
modifier = Modifier.weight(1f)
)
NavigationControls(webViewState)
// Example buttons to navigate or set cookies
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Button(onClick = {
// Navigate to a new URL
webViewState.loadUrl("https://www.example.com")
}) {
Text("Go to Example.com")
}
Button(onClick = {
// Set a custom cookie for example.com
webViewState.setCookie("https://www.example.com", "MyCookie=12345; Domain=example.com; Path=/")
}) {
Text("Set Cookie")
}
}
}
}
Explanation:
-
Buttons:
- Go to Example.com: Navigates the WebView to
https://www.example.com.
- Set Cookie: Sets a custom cookie for
example.com. The cookie format follows the standard Set-Cookie header format.
-
Integration: The MainContent composable integrates CustomWebView with navigation controls and buttons to interact with the WebView.
-
Note: Ensure that you replace "https://www.example.com" and the cookie string with actual URLs and valid cookie formats as needed.
7. Putting It All Together
Here's the final structure of your project:
- MainActivity.kt: Hosts the
CustomWebView and provides navigation controls.
- CustomWebView.kt: Contains the WebView composable with cookie management and loading indicators.
- WebViewState.kt: Manages the state and interactions with the WebView.
Final MainActivity.kt
package com.example.osticket
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import com.example.osticket.ui.theme.OsticketTheme
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
OsticketTheme {
Scaffold(
topBar = {
TopAppBar(
title = { Text("Osticket WebView") },
actions = {
// Add any app actions if needed
}
)
},
modifier = Modifier.fillMaxSize()
) { innerPadding ->
Surface(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
color = MaterialTheme.colorScheme.background
) {
MainContent()
}
}
}
}
}
}
@Composable
fun MainContent() {
val context = LocalContext.current
val webViewState = remember { WebViewState(context) }
var showLoading by remember { mutableStateOf(false) }
Column(modifier = Modifier.fillMaxSize()) {
if (showLoading) {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.height(4.dp),
color = MaterialTheme.colorScheme.primary,
trackColor = Color.Transparent
)
}
CustomWebView(
state = webViewState,
onLoadingStateChanged = { isLoading ->
showLoading = isLoading
},
onCookiesRetrieved = { cookies ->
// Handle retrieved cookies if needed
},
modifier = Modifier.weight(1f)
)
NavigationControls(webViewState)
// Example buttons to navigate or set cookies
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
horizontalArrangement = Arrangement.SpaceEvenly
) {
Button(onClick = {
// Navigate to a new URL
webViewState.loadUrl("https://www.example.com")
}) {
Text("Go to Example.com")
}
Button(onClick = {
// Set a custom cookie for example.com
webViewState.setCookie("https://www.example.com", "MyCookie=12345; Domain=example.com; Path=/")
}) {
Text("Set Cookie")
}
}
}
}
8. Additional Recommendations
-
Persistent Storage for WebViewState: To maintain state across app restarts, consider persisting WebViewState using ViewModel and SavedStateHandle.
-
Security Considerations:
- Be cautious when enabling JavaScript and other WebView settings.
- Validate and sanitize any data passed to the WebView to prevent XSS attacks.
-
Error Handling: Enhance error handling by displaying user-friendly messages or retry options when page loading fails.
-
Permissions: If your WebView needs access to device resources (e.g., camera, location), ensure you handle permissions gracefully.
-
Testing: Test your WebView with various websites to ensure compatibility and handle edge cases.
-
Dependency Injection: For larger projects, consider using dependency injection (e.g., Hilt) to manage instances like WebViewState.
By following the above steps, you've modularized your WebView component, added loading indicators, and implemented cookie logging and storage. This setup makes your WebView reusable and adaptable for different websites, providing a robust foundation for your app.