1. Android代码
class MainActivity : AppCompatActivity() {
private lateinit var callJSBtn: Button
private lateinit var webView: WebView
private var ajObject: AjObject = AjObject()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initViews()
}
private fun initViews() {
callJSBtn = findViewById(R.id.call_js_btn)
callJSBtn.setOnClickListener(View.OnClickListener {
webView.post(Runnable {
webView.loadUrl("javascript:callJS('Message From Vue')")
})
})
webView = findViewById(R.id.web_view)
webView.settings.allowFileAccess = true
webView.settings.javaScriptEnabled = true
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(
view: WebView?,
url: String?
): Boolean {
view?.loadUrl(url)
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
}
}
webView.loadUrl("http://192.168.1.110:8080/")
webView.addJavascriptInterface(ajObject, "android")
}
}
class AjObject {
@JavascriptInterface
fun callJava(msg: String) : String {
return "Message From Android"
}
}
2. Vue代码
在Vue项目下创建utils/jsToAndroid.js
//jsToAndroid.js
const android = window.android
export {
android
}
在HelloWorld.vue中引入jsToAndroid.js
//HelloWorld.vue
{{ msg }}
Click
import {android} from '../utils/jsToJava'
export default {
data() {
return {
msg: "Hello"
}
},
mounted() {
window.callJS = this.callJS
},
methods: {
callJS(str) {
if (str !== undefined && str !== "") {
this.msg = str
}
// return "message from javascript"
},
callJava() {
this.msg = android.callJava('jack')
}
},
}
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
效果图
点击Call JavaScript,Android调用Vue
点击Click,Vue调用Android方法
来源:oschina
链接:https://my.oschina.net/yuewawa/blog/4329536