DSBridge is the best IOS/Android javascript Bridge on the planet. No one!

DSBridge

DSBridge is a communication bridge between H5 page and Native. It has the following characteristics:

  1. Cross-platform; Supports both ios and Android.
  2. Two-way call; Js can call native, native can call JS
  3. Support not only asynchronous invocation, but also page synchronous invocation (DSBridge is the only javascript Bridge that supports synchronous invocation)
  4. Support for progress callback, multiple returns (often used for file download progress, timers, etc.)
  5. Android supports Tencent X5 kernel
  6. Three terminals easy to use; It’s easy to use on either the front end or android or ios, greatly reducing integration/learning costs

For comparison with WebViewJavascriptBridge, go to DSBridge VS WebViewJavascriptBridge

The installation

  1. Add JitPack repository

    allprojects {
      repositories {
       ...
       maven { url 'https://jitpack.io'}}}Copy the code
  2. Add the dependent

    dependencies {
    	
    	 compile 'com. Making. Wendux: DSBridge - Android: 2.0 the SNAPSHOT'
    
    	// Use the Tencent X5 kernel to use this version
    	// compile 'com.github.wendux:DSBridge-Android:x5-SNAPSHOT'
        
        // Mainline version
    	//compile 'com.github.wendux:DSBridge-Android:master-SNAPSHOT'
    }
    Copy the code

use

Suppose Native implements two apis: testSyn and testAsyn. Parameters are passed in JSON. TestSyn is a synchronous API that returns results directly after execution. TestAsyn is an asynchronous API that may perform time-consuming operations.

Android

  1. Implement apis in Java

    public class JsApi{
        // For synchronous calls
        @JavascriptInterface
        String testSyn(JSONObject jsonObject) throws JSONException {
            // The return value type can only be String
            return jsonObject.getString("msg") + "[syn call]";
        }
        // For asynchronous calls
        @JavascriptInterface
        void testAsyn(JSONObject jsonObject, CompletionHandler handler) throws JSONException {
            handler.complete(jsonObject.getString("msg") +" [asyn call]"); }}Copy the code

    For security purposes, all apis must have “JavascriptInterface” annotations.

  2. Install the implemented API into the DWebView

    import wendu.dsbridge.DWebView
    ...
    DWebView dwebView= (DWebView) findViewById(R.id.dwebview);
    dwebView.setJavascriptInterface(new JsApi());
    Copy the code
  3. Invoke the Java API in the H5 page

    • Initialize dsBridge
    //cdn
    //<script src="https://unpkg.com/dsbridge/dist/dsbridge.js"> </script>
    //npm
    //npm install dsbridge
    var dsBridge=require("dsbridge")
    Copy the code
    • Call API

      // Synchronous call
      var str=dsBridge.call("testSyn", {msg: "testSyn"});
      
      // Asynchronous invocation
      dsBridge.call("testAsyn", {msg: "testAsyn"}, function (v) {
        alert(v);
      })
      
      Copy the code
  4. Native calls the javascript API in H5

    • Javascript registers apis for Native calls

      // Register an addition function for Native to call
       dsBridge.register('addValue',function(l,r){
           return l+r;
       })
      Copy the code
    • Call the javascript API in Java

      webView.callHandler("addValue".new Object[]{1."hello"},new OnReturnValue(){
             @Override
             public void onValue(String retValue) {
                Log.d("jsbridge"."call succeed,return value is "+retValue); }});Copy the code

      Note: Native calls to javascript apis must be made after “PageFinished”

IOS

For details about how to use the IOS software, see dsbridge-ios.

Javascript API

dsBridge

“DsBridge” is a global object that is available when dsBridge is initialized in the H5 page. It has two methods “call” and “register”;

bridge.call(method,[args,callback])

Function: Call Native API

Method: indicates the API function name

Args: parameter. Type: JSON. This parameter is optional

Callback (String returnValue): required only when calling asynchronous apis.

A synchronous invocation

If you’re an experienced developer, the second line will light up your eyes. Consider one of the biggest criticisms of Node. Currently, none of the cross-platform JsBridges support synchronization, and all calls to fetch values must pass a callback. There will be “callback hell”. DSBridge, however, has changed all that. Support for synchronization is one of the biggest highlights of DSBridge.

The asynchronous call

For more time-consuming apis, DSBridge provides asynchronous support, as shown in the third line above, where you need to pass a callback (if there are no arguments, the callback can be used as a second argument), which will be called when the API is complete, passing the result as a string.

dsBridge.register(methodName,function)

Register javascript apis for Native calls

Pay attention to

In order to be compatible with Android and IOS, DSBridge has two requirements for signing Native apis:

  1. The return value must be String, or null if there is no return value

  2. API parameters are passed through the JSONObject. If some APIS have no parameters, you need to declare them.

Return repeatedly

Normally, calling a method returns a result, one to one. Now, consider the following scenario:

There is a web page embedded in the app that displays a list of documents to download. Click the download button corresponding to the file in the web page to download the file and display the download progress in the web page.

Thinking: We implement the function of file download in Natvie. When clicking on an item on the web page, we call Native’s download method through JS. During the download process, Native keeps returning the progress to JS, and then JS updates the progress bar on the web page. The feature of this call is one js call, corresponding to native’s “multiple return”. Considering that many time-consuming tasks of Native may be returned multiple times (such as return progress), DSBridge supports “multiple return”, and DSBridge can be very convenient to deal with this case.

For a detailed example, see the DSBridge Example – Showing Native progress on a web page

Invoke Javascript

DWebView provides three apis for calling JS

void callHandler(String method, Object[] args) 
void callHandler(String method, Object[] args, CompletionHandler handler)
void evaluateJavascript(String script)
Copy the code

In the first two apis, method is a function name and args is an array of parameters, which can take strings, ints, longs, floats, doubles, and so on.

The first API is used to call js functions that have no return value. Null is passed if there are no arguments.

The second API is for scenarios where a returnValue is required, passing a CompletionHandler interface object that processes the returnValue in the complete(String returnValue) method.

The third API is used to execute arbitrary JS code with internal version compatibility.

Call time

DWebview can’t properly execute js code until the javascript context is initialized, which is usually done before the entire page is loaded. While DSBridge can catch when the javascript context is initialized, some JS apis may be declared at the end of the page, or even in a separate JS file (please don’t do this), If you call the JS API just after the javascript context has been initialized, the JS API may not be registered at this time, so it will fail. In conclusion, if the client calls the JS API actively, it should be called after onPageFinished. A simple example is as follows:

webView.setWebViewClient(new WebViewClient(){
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        // Expected return value
        webView.callHandler("test".new Object[]{1."hello"},new CompletionHandler(){
            @Override
            public void complete(String retValue) {
                Log.d("jsbridge"."call succeed,return value is "+retValue); }});// No return value is expected
        webView.callHandler("test".null); }});Copy the code

DWebview more

The following functions in DWebview are executed in the main thread; you do not have to manually switch threads

void loadUrl( String url) 
void loadUrl(final String url, Map<String, String> additionalHttpHeaders)
void evaluateJavascript(String script) 
Copy the code

DWebview already implements alert, Prompt, and comfirm dialog boxes. You can either leave them alone or customize them. It is worth mentioning that js code will block when calling the alert function under normal circumstances as long as the user does not close the Alert dialog box. However, considering that the alert dialog box only has a confirm button, that is to say, no matter the user closes or confirms it, js code flow will not be affected. Therefore, when the alert dialog box pops up in DWebview, js will be returned first, so that JS can continue to execute, and the prompt box can be closed when the user closes. If you want to block an alert, you can customize it. DWebview’s prompt and comfirm implementations are completely ecMA compliant and are blocked.

The last

If you like, welcome star! github: https://github.com/wendux/DSBridge-Android