Home » Java » Web apps in WebView android

Web apps in WebView android

Posted by: admin September 26, 2018 Leave a comment

Questions:

html script code

<script>
                    var object;
                    function doit() {
                        object = MyBridge.NDInteraction.getObject();
                        alert(typeof object);
                        object.toast();
                        object.toast(function(err) {
                            object.toast();
                        });
                    }   
</script>

This call return native object to js

object = MyBridge.NDInteraction.getObject();

This line is call to native method

object.toast()

addJavascriptInterface to webview

webView.addJavascriptInterface(new NDInteraction(this, this), "NDInteraction");

NDInteraction JavascriptInterface class
public class NDInteraction {

    Context mContext;
    /**
     * Instantiate the interface and set the context
     */
    NDInteraction(Context c) {
        mContext = c;
    }

    /**
     * Show a toast from the web page
     */
    @JavascriptInterface
    public void alert(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }


    @JavascriptInterface
    public Object getObject() {
        return new TestObject(mContext, "Test");
    }

    @JavascriptInterface
    public void postObject(Object object) {
        Toast.makeText(mContext, object.toString(), Toast.LENGTH_SHORT).show();
    }
}

TestObject JavascriptInterface class

public class TestObject  extends JsStaticModule {

    private Context mContext;
    private String mName;

    public TestObject(Context context, String name) {
        mContext = context;
        mName = name;
    }

    @JSBridgeMethod
    public void toast(final JBCallback callback) {
        callback.apply(0);
    }

    @JSBridgeMethod
    public void toast() {
        Toast.makeText(mContext, mName, Toast.LENGTH_SHORT).show();
    }
}

This two issue

1) Return native object to JS

 @JavascriptInterface
        public Object getObject() {
            return new TestObject(mContext, "Test");
        }

2) Function as argument in method

Js code
object.toast(function(err) {
                        object.toast();
                    });

Java code
        @JavascriptInterface
            public void toast(JsCallback callback {
                Toast.makeText(mContext, mName, Toast.LENGTH_SHORT).show();
    }
Answers: