Skip to content

Instantly share code, notes, and snippets.

@Aaronphy
Last active June 15, 2023 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aaronphy/e0aa016dadbc4fa7209a63eff447d05f to your computer and use it in GitHub Desktop.
Save Aaronphy/e0aa016dadbc4fa7209a63eff447d05f to your computer and use it in GitHub Desktop.
Android Webview communication between native and javascript
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
package com.example.greetingcard
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import android.webkit.JavascriptInterface
import android.content.Context
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.viewinterop.AndroidView
import com.example.greetingcard.ui.theme.GreetingCardTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GreetingCardTheme {
MainContent()
}
}
}
}
@Composable
fun MainContent() {
Scaffold(
topBar = { TopAppBar(title = { Text("GFG | WebView", color = Color.White) }, backgroundColor = Color(0xff0f9d58)) },
content = { MyContent() }
)
}
class WebAppInterface(private val mContext: Context) {
/** Show a toast from the web page */
@JavascriptInterface
fun showToast(toast: String) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
}
}
@SuppressLint("SetJavaScriptEnabled")
@Composable
fun MyContent(){
// Declare a string that contains a url
val mUrl = "http://10.71.56.41:8000/"
// 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()
settings.javaScriptEnabled = true
addJavascriptInterface(WebAppInterface(context), "Android")
loadUrl(mUrl)
}
}, update = {
it.loadUrl(mUrl)
})
}
// For displaying preview in
// the Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MainContent()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment