Code Monkey home page Code Monkey logo

dsbridge-android's Introduction

DSBridge for Android

dsBridge

language license GitHub last commit x5

Modern cross-platform JavaScript bridge, through which you can invoke each other's functions synchronously or asynchronously between JavaScript and native applications.

Chinese documentation 中文文档
DSBridge-IOS:https://github.com/wendux/DSBridge-IOS
Tencent x5 webcore support

Notice

DSBridge v3.0 is a milestone version. Compared with v2.0, we have made a lot of changes. Note that v3.0 is incompatible with v2.0, but v2.0 will continue to maintain. If you are a new user, use >=v3.0.

DSBridge v3.0.0 change list

Features

  1. The three ends of Android, IOS and Javascript are easy to use, light and powerful, secure and strong
  2. Both synchronous and asynchronous calls are supported
  3. Support API Object, which centrally implements APIs in a Java Class or a Javascript object
  4. Support API namespace
  5. Support debug mode
  6. Support the test of whether API exists
  7. Support Progress Callback: one call, multiple returns
  8. Support event listener for Javascript to close the page
  9. Support Modal and Modeless popup box for javascript
  10. Support the X5 webcore of Tencent

Installation

  1. Add the JitPack repository to your build file

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

    dependencies {
     //compile 'com.github.wendux:DSBridge-Android:3.0-SNAPSHOT'
     //support the x5 browser core of Tencent
     //compile 'com.github.wendux:DSBridge-Android:x5-3.0-SNAPSHOT'
    }

Examples

See the wendu.jsbdemo/ package. run the app project and to see it in action.

To use dsBridge in your own project:

Usage

  1. Implement APIs in a Java class

    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]");
        }
    }

    For security reason, Java APIs must be with "@JavascriptInterface" annotation .

  2. Add API object to DWebView .

    import wendu.dsbridge.DWebView
    ...
    DWebView dwebView= (DWebView) findViewById(R.id.dwebview);
    dwebView.addJavascriptObject(new JsApi(), null);
  3. Call Native (Java/Object-c/swift) API in Javascript, and register javascript API.

    • Init dsBridge

      //cdn
      //<script src="https://unpkg.com/[email protected]/dist/dsbridge.js"> </script>
      //npm
      //npm install [email protected]
      var dsBridge=require("dsbridge")
    • Call Native API and register a javascript API for Native invocation.

      //Call synchronously 
      var str=dsBridge.call("testSyn","testSyn");
      
      //Call asynchronously
      dsBridge.call("testAsyn","testAsyn", function (v) {
        alert(v);
      })
      
      //Register javascript API for Native
       dsBridge.register('addValue',function(l,r){
           return l+r;
       })
  4. Call Javascript API in java

    dwebView.callHandler("addValue",new Object[]{3,4},new OnReturnValue<Integer>(){
         @Override
         public void onValue(Integer retValue) {
            Log.d("jsbridge","call succeed,return value is "+retValue);
         }
    });

Java API signature

In order to be compatible with IOS , we make the following convention on Java API signature:

  1. For synchronous API.

    public any handler(Object msg)

    The argument type must be Object and must be declared even if not need),and the type of return value is not limited.

  2. For asynchronous API.

    public void handler(Object arg, CompletionHandler handler)

Namespace

Namespaces can help you better manage your APIs, which is very useful in hybrid applications, because these applications have a large number of APIs. DSBridge (>= v3.0.0) allows you to classify API with namespace. And the namespace can be multilevel, between different levels with '.' division.

Debug mode

In debug mode, some errors will be prompted by a popup dialog , and the exception caused by the native APIs will not be captured to expose problems. We recommend that the debug mode be opened at the development stage. You can open debug mode :

DWebView.setWebContentsDebuggingEnabled(true)

Progress Callback

Normally, when a API is called to end, it returns a result, which corresponds one by one. But sometimes a call need to repeatedly return multipule times, Suppose that on the Native side, there is a API to download the file, in the process of downloading, it will send the progress information to Javascript many times, then Javascript will display the progress information on the H5 page. Oh...You will find it is difficult to achieve this function. Fortunately, DSBridge supports Progress Callback. You can be very simple and convenient to implement a call that needs to be returned many times. Here's an example of a countdown:

In Java

@JavascriptInterface
public void callProgress(Object args, final CompletionHandler<Integer> handler) {
    new CountDownTimer(11000, 1000) {
        int i=10;
        @Override
        public void onTick(long millisUntilFinished) {
            //setProgressData can be called many times util complete be called.
            handler.setProgressData((i--));
        }
        @Override
        public void onFinish() {
           //complete the js invocation with data; 
           //handler will be invalid when complete is called
            handler.complete(0);
        }
    }.start();
}

In Javascript

dsBridge.call("callProgress", function (value) {
    document.getElementById("progress").innerText = value
})

For the complete sample code, please refer to the demo project.

Javascript popup box

For Javascript popup box functions (alert/confirm/prompt), DSBridge has implemented them all by default, if you want to custom them, override the corresponding callback in WebChromeClient . The default dialog box implemented by DSBridge is modal. This will block the UI thread. If you need modeless, please refer to dwebview.disableJavascriptDialogBlock (bool disable).

Security

Before Android 4.2 (API 17), webview.addJavascriptInterface has security vulnerabilities, and DSBridge doesn't use it under 4.2 of the devices. Meanwhile, in order to prevent Javascript from calling unauthorized native functions, all Java APIs must be annotated with "@JavascriptInterface" , so you can use DSBridge safely.

DWebView

In DWebview, the following functions will execute in main thread automatically, you need not to switch thread by yourself.

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

API Reference

Java API

In Java, the object that implements the javascript interfaces is called Java API object.

dwebview.addJavascriptObject(Object object, String namespace)

Add the Java API object with supplied namespace into DWebView. The javascript can then call Java APIs with bridge.call("namespace.api",...).

If the namespace is empty, the Java API object have no namespace. The javascript can call Java APIs with bridge.call("api",...).

Example:

In Java

public class JsEchoApi {
    @JavascriptInterface
    public Object syn(Object args) throws JSONException {
        return  args;
    }

    @JavascriptInterface
    public void asyn(Object args,CompletionHandler handler){
        handler.complete(args);
    }
}
//namespace is "echo"
dwebView.addJavascriptObject(new JsEchoApi(),"echo");

In Javascript

// call echo.syn
var ret=dsBridge.call("echo.syn",{msg:" I am echoSyn call", tag:1})
alert(JSON.stringify(ret))  
// call echo.asyn
dsBridge.call("echo.asyn",{msg:" I am echoAsyn call",tag:2},function (ret) {
      alert(JSON.stringify(ret));
})
dwebview.removeJavascriptObject(String namespace)

Remove the Java API object with supplied namespace.

dwebview.callHandler(String handlerName, Object[] args)
dwebview.callHandler(String handlerName, OnReturnValue handler)
dwebview.callHandler(String handlerName, Object[] args,OnReturnValue handler)

Call the javascript API. If a handler is given, the javascript handler can respond. the handlerName can contain the namespace. The handler will be called in main thread.

Example:

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', More details to see the Demo project                    
dWebView.callHandler("syn.getInfo", new OnReturnValue<JSONObject>() {
    @Override
    public void onValue(JSONObject retValue) {
      showToast(retValue);
    }
});
dwebview.disableJavascriptDialogBlock(bool disable)

BE CAREFUL to use. if you call any of the javascript popup box functions (alert, confirm, and prompt), the app will hang, and the javascript execution flow will be blocked. if you don't want to block the javascript execution flow, call this method, the popup box functions will return immediately( confirm return true, and the prompt return empty string).

Example:

dwebview.disableJavascriptDialogBlock(true);

if you want to enable the block, just calling this method with the argument value false .

dwebview.setJavascriptCloseWindowListener(JavascriptCloseWindowListener listener)

DWebView calls listener.onClose when Javascript calls window.close. the default handler is closing the current active activity. you can provide a listener to add your hanlder .

Example:

dwebview.setJavascriptCloseWindowListener(new DWebView.JavascriptCloseWindowListener() {
    @Override
    public boolean onClose() {
        Log.d("jsbridge","window.close is called in Javascript");
        //If return false,the default handler will be prevented. 
        return false;
    }
});
dwebview.hasJavascriptMethod(String handlerName, OnReturnValue<Boolean> existCallback)

Test whether the handler exist in javascript.

Example:

 dWebView.hasJavascriptMethod("addValue", new OnReturnValue<Boolean>() {
    @Override
    public void onValue(Boolean retValue) {
     showToast(retValue);
    }
 });
DWebView.setWebContentsDebuggingEnabled(boolean enabled)

Set debug mode. if in debug mode, some errors will be prompted by a popup dialog , and the exception caused by the native APIs will not be captured to expose problems. We recommend that the debug mode be opened at the development stage.

Javascript API

dsBridge

"dsBridge" is accessed after dsBridge Initialization .

dsBridge.call(method,[arg,callback])

Call Java api synchronously and asynchronously。

method: Java API name, can contain the namespace。

arg: argument, Only one allowed, if you expect multiple parameters, you can pass them with a json object.

callback(String returnValue): callback to handle the result. only asynchronous invocation required.

dsBridge.register(methodName|namespace,function|synApiObject)
dsBridge.registerAsyn(methodName|namespace,function|asyApiObject)

Register javascript synchronous and asynchronous API for Native invocation. There are two types of invocation

  1. Just register a method. For example:

    In Javascript

    dsBridge.register('addValue',function(l,r){
         return l+r;
    })
    dsBridge.registerAsyn('append',function(arg1,arg2,arg3,responseCallback){
         responseCallback(arg1+" "+arg2+" "+arg3);
    })

    In Java

    webView.callHandler("addValue",new Object[]{1,6},new OnReturnValue(){
      @Override
      public void onValue(String retValue) {
        Log.d("jsbridge","call succeed,return value is: "+retValue);
      }
    });
    
     webView.callHandler("append",new Object[]{"I","love","you"},new OnReturnValue(){
       @Override
       public void onValue(String retValue) {
         Log.d("jsbridge","call succeed, append string is: "+retValue);
       }
     });

  2. Register a Javascript API object with supplied namespace. For example:

    In Javascript

    //namespace test for synchronous
    dsBridge.register("test",{
      tag:"test",
      test1:function(){
    	return this.tag+"1"
      },
      test2:function(){
    	return this.tag+"2"
      }
    })
      
    //namespace test1 for asynchronous calls  
    dsBridge.registerAsyn("test1",{
      tag:"test1",
      test1:function(responseCallback){
    	return responseCallback(this.tag+"1")
      },
      test2:function(responseCallback){
    	return responseCallback(this.tag+"2")
      }
    })

    Because JavaScript does not support function overloading, it is not possible to define asynchronous function and sync function of the same name。

    In Java

    webView.callHandler("test.test1",new OnReturnValue<String>(){
        @Override
        public void onValue(String retValue) {
            Log.d("jsbridge","Namespace test.test1: "+retValue);
        }
    });
    
    webView.callHandler("test1.test1",new OnReturnValue<String>(){
        @Override
        public void onValue(String retValue) {
            Log.d("jsbridge","Namespace test.test1: "+retValue);
        }
    });
dsBridge.hasNativeMethod(handlerName,[type])

Test whether the handler exist in Java, the handlerName can contain the namespace.

type: optional["all"|"syn"|"asyn" ], default is "all".

dsBridge.hasNativeMethod('testAsyn') 
//test namespace method
dsBridge.hasNativeMethod('test.testAsyn')
// test if exist a asynchronous function that named "testSyn"
dsBridge.hasNativeMethod('testSyn','asyn') //false
dsBridge.disableJavascriptDialogBlock(disable)

Calling dsBridge.disableJavascriptDialogBlock(...) has the same effect as calling dwebview.disableJavascriptDialogBlock(...) in Java.

Example:

//disable
dsBridge.disableJavascriptDialogBlock()
//enable
dsBridge.disableJavascriptDialogBlock(false)

Work with fly.js

As we all know, In browser, AJax request are restricted by same-origin policy, so the request cannot be initiated across the domain. However, Fly.js supports forwarding the http request to Native through any Javascript bridge, And fly.js has already provide the dsBridge adapter.Because the Native side has no the same-origin policy restriction, fly.js can request any resource from any domain.

Another typical scene is in the hybrid App, Fly.js will forward all requests to Native, then, the unified request management, cookie management, certificate verification, request filtering and so on are carried out on Native.

For the complete sample code, please refer to the demo project.

Finally

If you like DSBridge, please star to let more people know it , Thank you !

dsbridge-android's People

Contributors

biluochun avatar luckyshane avatar wendux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dsbridge-android's Issues

Two functions callback

Hello. Is it possible to make async call with 2 callbacks?

   function callAsyn() {
            dsBridge.call("testAsyn", {msg: "testAsyn"}, 
		function (v) {
                  alert(v)
	        }, 
		function (v) {
                  promt(v)
              })
    }

提个建议

android端侵入性过大,可以考虑不限定WebView

View.post(Runnable) will cause memory leak

there are some memory leaks in DWebView class
// line 618
public void loadUrl(final String url, final Map<String, String> additionalHttpHeaders) {
post(new Runnable() {
@OverRide
public void run() {
DWebView.super.loadUrl(url, additionalHttpHeaders);
}
});

}
// line 592
public void loadUrl(final String url) {
post(new Runnable() {
@OverRide
public void run() {
DWebView.super.loadUrl(url);
}
});

}
// line 534
public void evaluateJavascript(final String script) {
if (Looper.getMainLooper() == Looper.myLooper()) {
_evaluateJavascript(script);
} else {
post(new Runnable() {
@OverRide
public void run() {
_evaluateJavascript(script);
}
});

}
}
, which will cause serious crash(java.lang.OutOfMemoryError), i recommend that you should use the WeakHandler.post(Runnable) instead of using View.post(Runnable)

What's the license?

this is a super simple implementation of js bridge, and our team is very glad to integrate DSBridge to our products, but we also have some concerns and want to patch it to meet those requirements.

so, what's the license of this repo? if it's MIT, that's very helpful.

and, we're happy to contribute back if we think our requirements could benefit others and the patches are works well.

thanks.

异步调用时报错

W/cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 3818 W/System.err: java.lang.reflect.InvocationTargetException W/System.err: at java.lang.reflect.Method.invoke(Native Method) W/System.err: at wendu.dsbridge.DWebView$InnerJavascriptInterface.call(DWebView.java:255) W/System.err: at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method) W/System.err: at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:41) W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102) W/System.err: at android.os.Looper.loop(Looper.java:150) W/System.err: at android.os.HandlerThread.run(HandlerThread.java:61) W/System.err: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference W/System.err: at wendu.dsbridge.DWebView.dispatchStartupQueue(DWebView.java:523) W/System.err: at wendu.dsbridge.DWebView.access$800(DWebView.java:53) W/System.err: at wendu.dsbridge.DWebView$1.dsinit(DWebView.java:414) W/System.err: ... 7 more D/dsBridge: Call failed:The parameter of "dsinit" in Java is invalid.

v3.0 change list

DSBridge v3.0 change list

DSBridge v3.0 is a milestone, Compared with v2.0.X, we have made a lot of changes. Note that V3.0 is incompatible with V2.0, but v2.0 will continue to maintain. If you are a new user, use >=v3.0

In Java

  1. Deprecateddwebview.setJavascriptInterface , use addJavascriptObject instead.
  2. New: addJavascriptObject(Object object, String namespace)
  3. New: removeJavascriptObject(String namespace)
  4. New: disableJavascriptDialogBlock(bool disable)
  5. New: hasJavascriptMethod(String handlerName, OnReturnValue<Boolean> existCallback)
  6. New: setJavascriptCloseWindowListener(JavascriptCloseWindowListener listener)
  7. New: DWebView.setWebContentsDebuggingEnabled(boolean enabled)
  8. New feature: Support namespace
  9. Changed: Java API signature changed
  10. Changed: callHandler can be called at any time.
  11. Changed: change minSdkVersion to 11.

In Javascript

  1. New: hasNativeMethod(handlerName,[type])
  2. New: disableJavascriptDialogBlock(disable)
  3. New: registerAsyn(methodName|namespace,function|asyApiObject)
  4. Changed: register(methodName|namespace,function|synApiObject)
  5. New feature: Support namespace

使用vue框架时,dsBridge不起作用

使用vue框架时,把dsBridge.call("testSyn", {msg: "clickEvent"}) 放在vue的methods,无法调用原生代码,是什么原因,代码如下
methods:{
clickEvent:function () {
console.log("clickEvent")
alert(dsBridge.call("testSyn", {msg: "clickEvent"}))
}
}

关于回调的问题,RT

webView 原生的evaluateJavascript()方法,会有一个回调onReceiveValue来返回结果。但是只是4.4之后的方法,4.4之前用不了。可是在这里面没有找到兼容的方式啊,求解

求助,出现error

用的是2.0版本,js调用Andorid端带参数的方法,成功接收到了传过来的参数,然后会出现下面的弹窗提示。这是什么原因呢?
ERROR!
Call failed:Function does not exist or parameter is invalid [null]

Android 4.4.4 error

09-01 10:59:33.932 4498-4498/com.hzty.rysj.leyou W/System.err: java.lang.NoClassDefFoundError: android.support.v7.widget.AppCompatDrawableManager$ColorFilterLruCache
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.widget.AppCompatDrawableManager.(SourceFile:103)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(Unknown Source)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AppCompatDelegateImplBase.(Unknown Source)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AppCompatDelegateImplV9.(Unknown Source)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AppCompatDelegateImplV11.(Unknown Source)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AppCompatDelegateImplV14.(Unknown Source)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AppCompatDelegate.create(Unknown Source)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AppCompatDelegate.create(Unknown Source)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AppCompatDialog.getDelegate(SourceFile:156)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AppCompatDialog.(SourceFile:52)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AlertDialog.(SourceFile:98)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.support.v7.app.AlertDialog$Builder.create(Unknown Source)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at wendu.dsbridge.DWebView$2.onJsAlert(SourceFile:318)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at com.android.webview.chromium.WebViewContentsClientAdapter.handleJsAlert(WebViewContentsClientAdapter.java:612)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at com.android.org.chromium.android_webview.AwContentsClientBridge.handleJsAlert(AwContentsClientBridge.java:72)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:24)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.os.Looper.loop(Looper.java:136)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5103)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
09-01 10:59:33.936 4498-4498/com.hzty.rysj.leyou W/System.err: at dalvik.system.NativeStart.main(Native Method)

Json接收数据反斜杠转换问题

您好!我想问下,如果是回传的json的话 我Android这边接收到的url连接的“/”会变成“/”,这个是什么问题呢?我先暂时只能用url的encode和decode来解决

安卓4.4版本,WebChromeClient的openFileChooser方法没有回调

public void openFileChooser(ValueCallback uploadMsg, String acceptType, String capture) {}

一个简单的 页面。在安卓系统4.4版本,用原生的webview可以响应该方法。DWebview响应不了。控制台输出了这个日志
chromium: [INFO:aw_web_contents_delegate.cc(230)] File Chooser result: mode = 0, file paths =

哥,帮我看看这个啥问题

代码问题

能否一起维护
QQ:14876534
微信:14876534

android 4.2安全性问题

在native编写代码方法名称上需要加上@JavascriptInterface 但是怎么保证4.2以下的安全性问题呢

error

01-19 17:07:25.993 28912-28912/wendu.jsbdemo E/Web Console: Uncaught ReferenceError: getJsBridge is not defined at file:///android_asset/test.html:42
01-19 17:07:25.993 28912-28927/wendu.jsbdemo D/jsbridge: call succeed,return value is 1hello
01-19 17:08:09.423 28912-28912/wendu.jsbdemo E/Web Console: Uncaught TypeError: Cannot call method 'call' of undefined at file:///android_asset/test.html:46

案例运行出错

错误日志:

01-04 16:19:37.007 3363-3932/wendu.jsbdemo W/System.err: java.lang.IllegalAccessException: Class java.lang.Class<wendu.dsbridge.DWebView$1> cannot access  method void wendu.jsbdemo.JsApi.testAsyn(org.json.JSONObject, wendu.dsbridge.CompletionHandler) of class java.lang.Class<wendu.jsbdemo.JsApi>
01-04 16:19:37.007 3363-3932/wendu.jsbdemo W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
01-04 16:19:37.007 3363-3932/wendu.jsbdemo W/System.err:     at wendu.dsbridge.DWebView$1.call(DWebView.java:126)
01-04 16:19:37.007 3363-3932/wendu.jsbdemo W/System.err:     at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
01-04 16:19:37.007 3363-3932/wendu.jsbdemo W/System.err:     at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:53)
01-04 16:19:37.007 3363-3932/wendu.jsbdemo W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
01-04 16:19:37.007 3363-3932/wendu.jsbdemo W/System.err:     at android.os.Looper.loop(Looper.java:148)
01-04 16:19:37.008 3363-3932/wendu.jsbdemo W/System.err:     at android.os.HandlerThread.run(HandlerThread.java:61)

然后定位到DWebView下的
ret = method.invoke(jsb, arg);
这行代码

机型:一加一代 Android6.0

js调用原生方法的问题

目前发现两个问题:
1)dsbridge.js在定义call方法的时候,如果入参是number类型的0,会导致结果data是空json,而不是0
z h eijcf d 4wdg 4opt
原先的这个方法,在入参是number 0 的时候,直接是false了,这样就出错了

2)DWebView的InnerJavascriptInterface里面的call方法,在获取方法的时候,考虑到继承相关的问题,应该使用getMethod,不是getDeclaredMethod

Native调用js未获取到

demo中addValue为什么没有获取到返回值?而且js加的alert也没有弹呢?

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

dsBridge.register('addValue',function(r,l){
alert('调用goback');
return r+l;
})

call()函数返回值

@wendux 你好!DWebView中的call方法返回的是String,需要需要返回Map<>,在DWebView中重写了一个callObject方法,大体原先的call()方法差不多,把返回的object转换成了map返回,在injectJs()中,仿照原先的注入方法,加上了一段新的js脚本,但是这样调用不到?可以指导一下思路吗?

webview内核初始化

@wendux 你好!我想问下,webview实例化的时候,初始化浏览器内核所花的时间有什么方法可以检测吗?

库下载不动

compile 'com.github.wendux:DSBridge-Android:2.0-SNAPSHOT' 这个无法下载,已翻墙

加一个列表滑动很卡

首先,此库确实调用方便,很好用,但是遇到一个问题使用dswebview加载一个列表滑动的时候很卡,但是使用原生的webview不会出现这个问题,希望作者优化此处

怎么使用x5内核呢?

集成X5 SDK的时候需要在Application中 QbSdk.initX5Environment来初始化,这个库不需要吗?
使用x5的时候只需要改compile就可以了吗?layout中还是使用<wendu.dsbridge.DWebView/>吗?
DSBridge-Android:x5-SNAPSHOT也升级3.0版本了吗?

急急急!!!给JS回调结果时出现的异常

在Android4.2.2版本的机器上,js调用本地Java代码之后给js回调返回值的时候出现了:"Uncaught SyntaxError: Invalid or unexpected token", source: (1)异常,但是在Android4.4版本上不会出现这个异常。

Dependency on fly

Do I have to use fly like your demo does ? I assume fly is designed to be browser / webview agnostic and that's part of why you wrote it ? Also to make model and browser usage agnostic.

I write all my Js code in golang and transpired into Js and soon WASM and load it into the webview.
I would prefer to not have to write a importer for you fly Js code into my golang code.
But I can if required, hence why I am seeking your advice about fly being needed.

在Android 4.4 里面 反射代理对象的时候,拿不到已注册的方法

Object jsb = DWebView.this.javaScriptNamespaceInterfaces.get(nameStr[0]);

这个拿到设置的对象了,但是
jsb.getClass().getMethods(); 里面没有已设置对象对应的函数
报 错 ,“Not find method methodName implementation! please check if the signature or namespace of the method is right ”

在 7.0 的系统里面就是正常的 。

这个是bug 么?

How to implement DSBridge in existing webview?

Maybe this is a dumb question... But I cannot figure out how to implement this bridge into a already existing WebView. Is it explained somewhere? Is it actually possible?

Thank you so much in advance for any help you are able to provide!

setJavaScriptInterface()方法

在调用的地方,这个只能set一个类是吧?我发现后边set的类,反射找方法的时候,都会在首次调用成功那个方法所在类中去找,写在其他类中的就找不到方法了

Uncaught ReferenceError:Cannot call method 'apply' of undefined at null

android 4.2
clone 下来的代码 没动
10-25 11:52:54.063 29187-29187/wendu.jsbdemo E/Web Console: Uncaught ReferenceError: dsBridge is not defined at file:///android_asset/test.html:45

10-25 11:52:54.213 29187-29187/wendu.jsbdemo E/Web Console: Uncaught TypeError: Cannot call method 'apply' of undefined at null:1

可是已经初始化了
//dsbridge初始化化代码
window._dsbridge&&_dsbridge.init();

    console.log(dsBridge)

==============

这么写dsBridge 是有值的
function callSyn() {
console.log(dsBridge)
alert(dsBridge.call("testSyn", {msg: "testSyn"}))
}

apply 没定义?谢谢!

注:后来发现在其他设备上是没问题的(新设备是android 5.0),可能和webview内核有关系,还没进一步验证

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.