As we all know, some functions of the app may use H5 development, which will inevitably encounter mutual calls between java and js. Android uses WebViewJavascriptBridge to realize the interaction between js and java. Here is an introduction Next, use the JsBridge third-party library.
github portal: https://github.com/lzyzsd/JsBridge
Java and js call each other as follows:
java sends data to js, and js receives it And pass it back to java
Similarly, js sends data to java, java receives and passes it back to js
At the same time, both processes have "default reception" and "specified reception"
The approximate call flow chart is as follows :
project build.gradle
repositories { // ... maven { url "https://jitpack.io" } }
app build.gradle
dependencies { compile 'com.github.lzyzsd:jsbridge:1.0.4'}
xml Directly usecom.github.lzyzsd.jsbridge.BridgeWebView
instead of nativeWebView
Place two moreButton
for testing use
Simply place two buttons in the html file to send data and provide printing information at the same time
Title
打印信息
Here I am running a simple django project locally and set up a service for use
webView.loadUrl("http://10.0.0.142:8000/cake/jsbridge");
webview
Loading page
button
Register to listen
javaToJsDefault.setOnClickListener(this); javaToJsSpec.setOnClickListener(this);
Button click event, java passes Data to js
//java传递数据给js @Override public void onClick(View v) { switch (v.getId()) { case R.id.java_to_js_default: //默认接收 webView.send("发送数据给js默认接收", new CallBackFunction() { @Override public void onCallBack(String data) { //处理js回传的数据 Toast.makeText(WebTestActivity.this, data, Toast.LENGTH_LONG).show(); } }); break; case R.id.java_to_js_spec: //指定接收参数 functionInJs webView.callHandler("functionInJs", "发送数据给js指定接收", new CallBackFunction() { @Override public void onCallBack(String data) { //处理js回传的数据 Toast.makeText(WebTestActivity.this, data, Toast.LENGTH_LONG).show(); } }); break; default: break; } }
jsWebViewJavascriptBridge
Register event monitoring and receive data