DSBridge Android

repository·master·Indexed 26 days ago

https://github.com/wendux/dsbridge-android

A modern cross-platform JavaScript bridge for Android and iOS enabling synchronous and asynchronous function calls between native code and JavaScript. It supports progress callbacks for multiple returns, namespace grouping for APIs, and integration with Fly.js for cross-domain requests. Key features include DWebView for managing Java-to-JS communication, @JavascriptInterface for exposing native methods, and tools to handle JavaScript dialog blocking and window.close() events.

Tokens
4K
Snippets
9
Records
29
Agent score
84%

What's inside dsbridge-android

  1. Enable Debug Mode

    master

    In debug mode, errors are presented via popups and native API exceptions are not automatically caught, allowing you to expose and fix issues during development. It is highly recommended to enable this during development.

    DWebView.setWebContentsDebuggingEnabled(true)
  2. Use DSBridge with Fly.js for Cross-Origin Requests

    master

    DSBridge can be used with Fly.js to bypass CORS (Cross-Origin Resource Sharing) restrictions.

    By using the Fly.js adapter for DSBridge, AJAX requests can be redirected from the JavaScript environment to the native Android side. Since the native side is not subject to the same-origin policy, it can fetch resources from any domain. This allows developers to manage requests, certificate validation, cookies, and access control centrally on the native side.

  3. Install DSBridge for Android via JitPack

    master

    To use DSBridge in your Android project, add the JitPack repository to your allprojects block and then add the dependency to your dependencies block.

    Note: If you need to support the Tencent X5 browser core, use the x5-3.0-SNAPSHOT version instead.

  4. Use DSBridge with Fly.js for cross-domain requests

    master
    Fly.js supports forwarding HTTP requests to Native via DSBridge. Since the Native side is not restricted by the browser's Same-Origin Policy, using the Fly.js DSBridge adapter allows your web content to request resources from any domain. This is useful for unified request management, cookie management, and certificate verification on the Native side.
  5. Implement and Register Java APIs

    master

    DSBridge allows you to manage APIs by creating a Java class. For security, all methods intended for Javascript access must be annotated with @JavascriptInterface.

    To use them, instantiate your API class and add it to a DWebView instance using addJavascriptObject.

  6. Implement Native Java APIs for DSBridge

    master

    To expose Java methods to JavaScript, create a class and annotate the methods with @JavascriptInterface. DSBridge follows specific signature conventions to ensure compatibility with iOS:

    1. Synchronous API: Must accept an Object as the first argument and return a value.
      • Signature: public any handler(Object msg)
    2. Asynchronous API: Must accept an Object and a CompletionHandler.
      • Signature: public void handler(Object arg, CompletionHandler handler)
    public class JsApi{
        // for synchronous invocation
        @JavascriptInterface
        public String testSyn(Object msg)  {
            return msg + "[syn call]";
        }
    
        // for asynchronous invocation
        @JavascriptInterface
        public void testAsyn(Object msg, CompletionHandler handler) {
            handler.complete(msg+" [ asyn call]");
        }
    }
  7. Configure Debug Mode in DWebView

    master

    Use DWebView.setWebContentsDebuggingEnabled(boolean enabled) to control the error handling behavior during development.

    • Enabled (true): Errors are shown via popups, and native API exceptions are not automatically caught. This is highly recommended during development to expose issues immediately.
    • Disabled (false): Errors do not trigger popups, and exceptions are automatically caught to prevent the app from crashing.
  8. Implement Progress Callbacks (One call, multiple returns)

    master

    DSBridge supports Progress Callback, allowing a single native call to return multiple values to JavaScript (e.g., for download progress).

    In Java, use handler.setProgressData(data) to send intermediate updates and handler.complete(data) to finish the call. In JavaScript, the callback function will be triggered for every update.

    // Java implementation
    @JavascriptInterface
    public void callProgress(Object args, final CompletionHandler<Integer> handler) {
        new CountDownTimer(11000, 1000) {
            int i=10;
            @Override
            public void onTick(long millisUntilFinished) {
                // Send progress data multiple times
                handler.setProgressData((i--));
            }
            @Override
            public void onFinish() {
                // Complete the invocation
                handler.complete(0);
            }
        }.start();
    }
    // JavaScript usage
    dsBridge.call("callProgress", function (value) {
        document.getElementById("progress").innerText = value
    })
  9. Call JavaScript APIs from Java

    master

    Use dwebview.callHandler to invoke JavaScript functions from the native Android side.

    • handlerName: The name of the JavaScript API (can include a namespace).
    • args: An array of arguments passed to the JavaScript function.
    • handler: An OnReturnValue callback used to receive the result from JavaScript. Note: The handler is executed on the main thread.
    dWebView.callHandler("append", new Object[]{"I", "love", "you"}, new OnReturnValue<String>() {
        @Override
        public void onValue(String retValue) {
            Log.d("jsbridge", "call succeed, append string is: " + retValue);
        }
    });
    
    // Call with namespace 'syn'
    dWebView.callHandler("syn.getInfo", new OnReturnValue<JSONObject>() {
        @Override
        public void onValue(JSONObject retValue) {
          showToast(retValue);
        }
    });