After searching for answers on various sites without success, I am reaching out for help with a specific issue. I am using vuejs with typescript and a webview in an android app. My goal is to have a button in the android app call a vuejs function, and vice versa, have a function in javascript call an android function. However, neither of these functionalities are working for me. I have tried multiple solutions but none have worked so far. If anyone has any insight on how to solve this issue, please let me know. I have included the relevant code snippets below. The URL path is correct and the page is loading in the webview, with "Home" being routed to "http://url/"
Home js
<template>
<div class="home">
<h1>This is an Home page</h1>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
name: 'Home',
methods:{
getAlert(){
alert(11111);
},
getWebViewAlert(toast:String){
android.showToast(toast);
}
}
})
interface WebAppInterface{ // eslint-disable-line no-unused-vars
showToast(toast: String) : void;
}
declare var android: WebAppInterface;// eslint-disable-line no-unused-vars
</script>
MainActivity.kt
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val webviewSetting = binding.webview.settings
webviewSetting.javaScriptEnabled = true
webviewSetting.setSupportMultipleWindows(false)
webviewSetting.javaScriptCanOpenWindowsAutomatically = false
webviewSetting.loadWithOverviewMode = true
webviewSetting.useWideViewPort = true
webviewSetting.setSupportZoom(false)
webviewSetting.builtInZoomControls = false
webviewSetting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
webviewSetting.cacheMode = WebSettings.LOAD_NO_CACHE
webviewSetting.domStorageEnabled =true
binding.webview.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
binding.webview.loadUrl("javascript:getAlert()")
}
}
binding.webview.webChromeClient = WebChromeClient()
//binding.webview.addJavascriptInterface(WebAppInterface(this),"android")
binding.webview.loadUrl(url)
binding.button.setOnClickListener {
binding.webview.loadUrl("javascript:getAlert()")
}
}
class WebAppInterface internal constructor(c: Context) {
var mContext: Context
@JavascriptInterface
fun showToast(toast: String) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
}
init {
mContext = c
}
}
Error in android studio
I/chromium: [INFO:CONSOLE(1)] "Uncaught ReferenceError: getAlert is not defined", source: url (1)
updated code
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify'
Vue.config.productionTip = false
let HomeVue; // eslint-disable-line no-unused-vars
new Vue({
router,
store,
vuetify,
mounted(){
HomeVue = this
},
methods:{
getAlert(){
return this;
}
},
render: h => h(App)
}).$mount('#app')