Compose WebView Part 8 | Navigation Go To Previous Page

 Jetpack Compose WebView Handling Back Navigation And Go To Previous Page

The WebViewClient listens for onPageStarted which checks if the WebView can navigate backwards and then updates backEnabled. This causes a recomposition which toggles the BackHandler on and off.

I've also moved loadUrl out of the update function and into factory because update is called every time there's a recomposition whereas factory is only called the once. This may or may not be relevant based on your implementation.

In this example, we are assigning the WebView to an external var so that's what I've done here.

package com.blogspot.boltuix import android.annotation.SuppressLint import android.graphics.Bitmap import android.os.Bundle import android.view.ViewGroup import android.webkit.WebView import android.webkit.WebViewClient import androidx.activity.ComponentActivity import androidx.activity.compose.BackHandler import androidx.activity.compose.setContent import androidx.compose.runtime.* 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){ var backEnabled by remember { mutableStateOf(false) } var webView: WebView? = null // 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 play video on a web view settings.javaScriptEnabled = true webViewClient = object : WebViewClient() { override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {  backEnabled = view.canGoBack() } }  loadUrl(url) webView = this } }, update = {  webView = it // it.loadUrl(url) }) BackHandler(enabled = backEnabled) {  webView?.goBack() } } 

..

GET full source code on Github:

https://github.com/BoltUIX/Compose-Web-View


..

Post a Comment

Previous Post Next Post