Search code examples
androidkotlinandroid-jetpackandroid-jetpack-compose

Is there a way to open a webpage on click of IconButton from the TopAppBar in a Compose Scaffold?


I am new to Jetpack, particularly Compose, and am struggling to figure out a way to open a website or launch the Chrome Browser on the click of an IconButton located in the TopAppBar. Should I perform this operation by either invoking a "linkToWebpage()" function I can write, or simply inline with the onClick = {} function of the IconButton? How would I do this? I am using the Navigation library for in-app navigation with great success, but am struggling to load a webpage. Note I have elided some code for readability. Thanks for the time and help!

@Composable
fun HomeScreen() {
   val navController = rememberNavController()

   ...

Scaffold(
        topBar = {
            TopAppBar(
                    title = {},
                    navigationIcon =
                    {
                        IconButton(onClick = { linkToWebpage() }) {
                            Icon(Icons.Filled.Favorite)
                        }
                    }
                    ,
                    // TODO get appbar color from global theme.
                    backgroundColor = Color.DarkGray,
            )
        },
        bottomBar = {       
           ...
        }
) {

    NavHost(navController, startDestination = Screen.Courses.route) {
        ...
    }
}

Solution

  • Wow I spent way too much time on this but was able to figure out how to start and activity that opens the web browser from within the composable function. By passing the 'linkToWebPage' function the context via

    val context = ContextAmbient.current
    

    then invoking the function with this as a param

    IconButton(onClick = { linkToWebpage(context) }) {
        Icon(Icons.Filled.Favorite)
    }
    

    I was then able to start the activity in the function I wrote as below

    fun linkToWebpage(context: Context) {
         //val context = ContextAmbient.current
         val openURL = Intent(Intent.ACTION_VIEW)
         openURL.data = Uri.parse("https://www.example.com/")
         startActivity(context, openURL, null )
    }
    

    Hope this is helpful to someone!