class LoginStateManager(private val context: Context) {
private val prefs: SharedPreferences = context.getSharedPreferences(
"osticket_prefs",
Context.MODE_PRIVATE
)
@Composable
fun LoginScreen(onLoginSuccess: (Boolean) -> Unit) {
var showWebView by remember { mutableStateOf(false) }
var isAdminLogin by remember { mutableStateOf(false) }
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun CustomWebView(
url: String,
onUrlChange: (String) -> Unit = {},
onLoadingStateChange: (Boolean) -> Unit = {},
onCookiesReceived: (List) -> Unit = {},
onError: (String) -> Unit = {},
onPageFinished: () -> Unit = {},
enableJavaScript: Boolean = true,
allowZoom: Boolean = false,
userAgent: String? = null
) {
val context = LocalContext.current
val cookieManager = CookieManager.getInstance().apply {
setAcceptCookie(true)
}
// Remember the WebView to preserve its state across recompositions
val webView = remember {
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
// Set third party cookies for this specific WebView instance
cookieManager.setAcceptThirdPartyCookies(this, true)
// Initialize WebViewClient with overridden methods
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
onLoadingStateChange(true)
url?.let { onUrlChange(it) }
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
onLoadingStateChange(false)
getCurrentCookies(view)
onPageFinished()
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
request?.url?.toString()?.let { onUrlChange(it) }
return false
}
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
error?.description?.toString()?.let { onError(it) }
}
private fun getCurrentCookies(view: WebView?) {
view?.url?.let { currentUrl ->
val cookies = cookieManager.getCookie(currentUrl)?.split(";")?.mapNotNull { cookieString ->
val parts = cookieString.trim().split("=", limit = 2)
if (parts.size == 2) {
Cookie(parts[0], parts[1])
} else {
null
}
} ?: emptyList()
onCookiesReceived(cookies)
}
}
}
webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
Log.d(
"WebView",
"${consoleMessage?.message()} -- From line ${consoleMessage?.lineNumber()} of ${consoleMessage?.sourceId()}"
)
return true
}
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
onLoadingStateChange(newProgress < 100)
}
}
// Configure WebView settings
settings.apply {
javaScriptEnabled = enableJavaScript
domStorageEnabled = true
javaScriptCanOpenWindowsAutomatically = true
loadWithOverviewMode = true
useWideViewPort = true
allowContentAccess = true
allowFileAccess = true
builtInZoomControls = allowZoom
displayZoomControls = false
setSupportZoom(allowZoom)
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
defaultTextEncodingName = "utf-8"
cacheMode = WebSettings.LOAD_DEFAULT // Enable caching
userAgent?.let { userAgentString = it }
// Enable database
databaseEnabled = true
}
// Load the initial URL once
loadUrl(url)
}
}
// Modified DisposableEffect to preserve state
DisposableEffect(Unit) {
onDispose {
webView.stopLoading()
// Don't clear cache or cookies
webView.loadUrl("about:blank")
// Only remove views, don't destroy the WebView
webView.removeAllViews()
}
}
// Embed the WebView into the Compose UI
AndroidView(
factory = { webView },
update = { /* No-op to prevent reloading */ }
)
}
// Data class for cookies
data class Cookie(
val name: String,
val value: String
)
// Example usage:
@Composable
fun WebViewScreen(url: String) {
var currentUrl by remember { mutableStateOf("") }
var isLoading by remember { mutableStateOf(true) }
var cookies by remember { mutableStateOf<List>(emptyList()) }
var error by remember { mutableStateOf<String?>(null) }
class LoginStateManager(private val context: Context) {
private val prefs: SharedPreferences = context.getSharedPreferences(
"osticket_prefs",
Context.MODE_PRIVATE
)
@Composable
fun LoginScreen(onLoginSuccess: (Boolean) -> Unit) {
var showWebView by remember { mutableStateOf(false) }
var isAdminLogin by remember { mutableStateOf(false) }
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun CustomWebView(
url: String,
onUrlChange: (String) -> Unit = {},
onLoadingStateChange: (Boolean) -> Unit = {},
onCookiesReceived: (List) -> Unit = {},
onError: (String) -> Unit = {},
onPageFinished: () -> Unit = {},
enableJavaScript: Boolean = true,
allowZoom: Boolean = false,
userAgent: String? = null
) {
val context = LocalContext.current
val cookieManager = CookieManager.getInstance().apply {
setAcceptCookie(true)
}
// Remember the WebView to preserve its state across recompositions
val webView = remember {
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
// Set third party cookies for this specific WebView instance
cookieManager.setAcceptThirdPartyCookies(this, true)
// Initialize WebViewClient with overridden methods
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
onLoadingStateChange(true)
url?.let { onUrlChange(it) }
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
onLoadingStateChange(false)
getCurrentCookies(view)
onPageFinished()
}
override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
): Boolean {
request?.url?.toString()?.let { onUrlChange(it) }
return false
}
override fun onReceivedError(
view: WebView?,
request: WebResourceRequest?,
error: WebResourceError?
) {
error?.description?.toString()?.let { onError(it) }
}
private fun getCurrentCookies(view: WebView?) {
view?.url?.let { currentUrl ->
val cookies = cookieManager.getCookie(currentUrl)?.split(";")?.mapNotNull { cookieString ->
val parts = cookieString.trim().split("=", limit = 2)
if (parts.size == 2) {
Cookie(parts[0], parts[1])
} else {
null
}
} ?: emptyList()
onCookiesReceived(cookies)
}
}
}
webChromeClient = object : WebChromeClient() {
override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
Log.d(
"WebView",
"${consoleMessage?.message()} -- From line ${consoleMessage?.lineNumber()} of ${consoleMessage?.sourceId()}"
)
return true
}
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
onLoadingStateChange(newProgress < 100)
}
}
// Configure WebView settings
settings.apply {
javaScriptEnabled = enableJavaScript
domStorageEnabled = true
javaScriptCanOpenWindowsAutomatically = true
loadWithOverviewMode = true
useWideViewPort = true
allowContentAccess = true
allowFileAccess = true
builtInZoomControls = allowZoom
displayZoomControls = false
setSupportZoom(allowZoom)
mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
defaultTextEncodingName = "utf-8"
cacheMode = WebSettings.LOAD_DEFAULT // Enable caching
userAgent?.let { userAgentString = it }
// Enable database
databaseEnabled = true
}
// Load the initial URL once
loadUrl(url)
}
}
// Modified DisposableEffect to preserve state
DisposableEffect(Unit) {
onDispose {
webView.stopLoading()
// Don't clear cache or cookies
webView.loadUrl("about:blank")
// Only remove views, don't destroy the WebView
webView.removeAllViews()
}
}
// Embed the WebView into the Compose UI
AndroidView(
factory = { webView },
update = { /* No-op to prevent reloading */ }
)
}
// Data class for cookies
data class Cookie(
val name: String,
val value: String
)
// Example usage:
@Composable
fun WebViewScreen(url: String) {
var currentUrl by remember { mutableStateOf("") }
var isLoading by remember { mutableStateOf(true) }
var cookies by remember { mutableStateOf<List>(emptyList()) }
var error by remember { mutableStateOf<String?>(null) }
To add a WebView that loads https://digital-land.org/osticket/scp/profile.php#preferences just above the logout button in the admin-only settings of your OSTicket application using Kotlin Jetpack Compose, you'll need to modify the SettingsScreen composable.
Here's a step-by-step guide to achieve this:
Understand the Current Structure:
The SettingsScreen is used for both admin and regular users.
The logout button is already present at the bottom of this screen.
We need to conditionally add a WebView only for admin users above the logout button.
Modify SettingsScreen.kt to Include WebView for Admins:
Below is the updated SettingsScreen composable that includes a WebView for admin users:
If the Settings screen has more content and you want to make it scrollable (especially when adding the WebView), consider wrapping the Column with a LazyColumn or ScrollableColumn. Here's how you can make the content scrollable:
The height assigned to the WebView (300.dp in the example) should be adjusted based on your UI requirements. Ensure that the WebView doesn't occupy too much or too little space, maintaining a balanced layout.
Ensure Permissions and WebView Configuration:
Make sure that your CustomWebView is properly configured to handle the URL and any specific requirements of the osticket profile page. From your provided CustomWebView.kt, it appears well-configured, but ensure that:
JavaScript is enabled if the page requires it.
Cookies are managed properly to maintain sessions.
Error handling is in place to handle any loading issues.
Testing:
After making these changes, thoroughly test the application:
Admin Users:
Navigate to the Settings screen.
Verify that the WebView loads the specified URL above the logout button.
Ensure that the WebView behaves as expected (navigation, interactions, etc.).
Regular Users:
Ensure that the WebView does not appear in the Settings screen.
The logout button should remain at the bottom as intended.
Optional Enhancements:
Responsive Design: Make the WebView responsive to different screen sizes and orientations.
Loading Indicators: Show a loading spinner or progress bar while the WebView content is loading.
Error Messages: Display user-friendly error messages if the WebView fails to load the content.
Complete Example:
For clarity, here's the complete modified SettingsScreen.kt with the WebView included for admin users:
Security: Be cautious when loading external URLs in WebViews. Ensure that the content is from a trusted source to prevent security vulnerabilities.
Summary:
By following the above steps, you've successfully integrated a WebView into the admin-only settings screen of your OSTicket application. This WebView displays the specified profile preferences page just above the logout button, enhancing the admin's ability to manage settings directly within the app.
If you encounter any issues or need further customization, feel free to ask!