Table of Contents
Simple analysis
Dependencies
java sends data to js
js sends data to java
Home Web Front-end JS Tutorial The use of jsbridge for the interaction between android and js

The use of jsbridge for the interaction between android and js

Apr 04, 2018 pm 01:49 PM
android javascript jsbridge


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

Simple analysis

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 :

Dependencies

project build.gradle

repositories {
    // ...
    maven { url "https://jitpack.io" }
}
Copy after login

app build.gradle

dependencies {
    compile 'com.github.lzyzsd:jsbridge:1.0.4'}
Copy after login

xml Directly use com.github.lzyzsd.jsbridge.BridgeWebView instead of native WebView
Place two more Button for testing use

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button        android:id="@+id/java_to_js_default"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="java发送给js默认接收"
        app:layout_constraintTop_toBottomOf="@+id/nav_bar" />

    <Button        android:id="@+id/java_to_js_spec"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="java发送给js指定接收"
        app:layout_constraintTop_toBottomOf="@+id/java_to_js_default" />

    <com.github.lzyzsd.jsbridge.BridgeWebView        android:id="@+id/webView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/java_to_js_spec" /></android.support.constraint.ConstraintLayout>
Copy after login

Simply place two buttons in the html file to send data and provide printing information at the same time

<html lang="en"><head>
    <meta charset="UTF-8">
    <title>Title</title></head><body><p>
    <button onClick="jsToJavaDefault()">js发送给java默认接收</button></p><br/><p>
    <button onClick="jsToJavaSpec()">js发送给java指定接收</button></p><br/><p id="show">打印信息</p></body></html>
Copy after login

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");
Copy after login

webview Loading page

java sends data to js

buttonRegister to listen

javaToJsDefault.setOnClickListener(this);
javaToJsSpec.setOnClickListener(this);
Copy after login

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;
        }
    }
Copy after login

js WebViewJavascriptBridgeRegister event monitoring and receive data

<script>

       //注册事件监听,初始化
       function setupWebViewJavascriptBridge(callback) {
           if (window.WebViewJavascriptBridge) {
               callback(WebViewJavascriptBridge)
           } else {
               document.addEventListener(                   &#39;WebViewJavascriptBridgeReady&#39;
                   , function() {
                       callback(WebViewJavascriptBridge)
                   },                   false
               );
           }
       }       //回调函数,接收java发送来的数据
       setupWebViewJavascriptBridge(function(bridge) {
           //默认接收
           bridge.init(function(message, responseCallback) {
               document.getElementById("show").innerHTML = &#39;默认接收到Java的数据: &#39; + message;               var responseData = &#39;js默认接收完毕,并回传数据给java&#39;;
               responseCallback(responseData); //回传数据给java
           });           //指定接收,参数functionInJs 与java保持一致
           bridge.registerHandler("functionInJs", function(data, responseCallback) {
               document.getElementById("show").innerHTML = &#39;指定接收到Java的数据: &#39; + data;               var responseData = &#39;js指定接收完毕,并回传数据给java&#39;;
               responseCallback(responseData); //回传数据给java
           });
       })

<script>
Copy after login

java is sent to js and is received by default

java Send to js to specify the reception

js sends data to java

js button click event. At the same time, the above WebViewJavascriptBridge registration listening callback function## is required. #

    //js传递数据给java
    function jsToJavaDefault() {
       var data = &#39;发送数据给java默认接收&#39;;
       window.WebViewJavascriptBridge.send(
           data
           , function(responseData) { //处理java回传的数据
              document.getElementById("show").innerHTML = responseData;
           }
       );
   }   function jsToJavaSpec() {
       var data=&#39;发送数据给java指定接收&#39;;
       window.WebViewJavascriptBridge.callHandler(           &#39;submitFromWeb&#39; //指定接收参数 submitFromWeb与java一致
           ,data
           , function(responseData) { //处理java回传的数据
              document.getElementById("show").innerHTML = responseData;
           }
       );
   }
Copy after login

java Monitor and receive data

        //默认接收
        webView.setDefaultHandler(new BridgeHandler() {            @Override
            public void handler(String data, CallBackFunction function) {
                String msg = "默认接收到js的数据:" + data;
                Toast.makeText(WebTestActivity.this, msg, Toast.LENGTH_LONG).show();

                function.onCallBack("java默认接收完毕,并回传数据给js"); //回传数据给js
            }
        });        //指定接收 submitFromWeb 与js保持一致
        webView.registerHandler("submitFromWeb", new BridgeHandler() {            @Override
            public void handler(String data, CallBackFunction function) {
                String msg = "指定接收到js的数据:" + data;
                Toast.makeText(WebTestActivity.this, msg, Toast.LENGTH_LONG).show();

                function.onCallBack("java指定接收完毕,并回传数据给js"); //回传数据给js
            }
        });
Copy after login
js is sent to java for default reception


js is sent to java for specified reception


At this point, the usage process of jsBridge is completed.

Related recommendations:

WeChat browser built-in JavaScript object WeixinJSBridge usage examples_javascript skills


The above is the detailed content of The use of jsbridge for the interaction between android and js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:23 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Samsung Galaxy S25 Ultra leaks in first render images with rumoured design changes revealed Sep 11, 2024 am 06:37 AM

OnLeaks has now partnered with Android Headlines to provide a first look at the Galaxy S25 Ultra, a few days after a failed attempt to generate upwards of $4,000 from his X (formerly Twitter) followers. For context, the render images embedded below h

IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size IFA 2024 | TCL\'s NXTPAPER 14 won\'t match the Galaxy Tab S10 Ultra in performance, but it nearly matches it in size Sep 07, 2024 am 06:35 AM

Alongside announcing two new smartphones, TCL has also announced a new Android tablet called the NXTPAPER 14, and its massive screen size is one of its selling points. The NXTPAPER 14 features version 3.0 of TCL's signature brand of matte LCD panels

Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Vivo Y300 Pro packs 6,500 mAh battery in a slim 7.69 mm body Sep 07, 2024 am 06:39 AM

The Vivo Y300 Pro just got fully revealed, and it's one of the slimmest mid-range Android phones with a large battery. To be exact, the smartphone is only 7.69 mm thick but features a 6,500 mAh battery. This is the same capacity as the recently launc

Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Samsung Galaxy S24 FE billed to launch for less than expected in four colours and two memory options Sep 12, 2024 pm 09:21 PM

Samsung has not offered any hints yet about when it will update its Fan Edition (FE) smartphone series. As it stands, the Galaxy S23 FE remains the company's most recent edition, having been presented at the start of October 2023. However, plenty of

New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades New report delivers damning assessment of rumoured Samsung Galaxy S25, Galaxy S25 Plus and Galaxy S25 Ultra camera upgrades Sep 12, 2024 pm 12:22 PM

In recent days, Ice Universe has been steadily revealing details about the Galaxy S25 Ultra, which is widely believed to be Samsung's next flagship smartphone. Among other things, the leaker claimed that Samsung only plans to bring one camera upgrade

Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Xiaomi Redmi Note 14 Pro Plus arrives as first Qualcomm Snapdragon 7s Gen 3 smartphone with Light Hunter 800 camera Sep 27, 2024 am 06:23 AM

The Redmi Note 14 Pro Plus is now official as a direct successor to last year'sRedmi Note 13 Pro Plus(curr. $375 on Amazon). As expected, the Redmi Note 14 Pro Plus heads up the Redmi Note 14 series alongside theRedmi Note 14and Redmi Note 14 Pro. Li

iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship iQOO Z9 Turbo Plus: Reservations begin for the potentially beefed-up series flagship Sep 10, 2024 am 06:45 AM

OnePlus'sister brand iQOO has a 2023-4 product cycle that might be nearlyover; nevertheless, the brand has declared that it is not done with itsZ9series just yet. Its final, and possibly highest-end,Turbo+variant has just beenannouncedas predicted. T

See all articles