开发者

How to use WebView.addJavascriptInterface to bind java class with javascript function format as "A.B.func()"

I want to support some self-define JavaScript interface with format "A.B.func()" on my app's WebView activity.

Here is a sample

The web page's html&js code is such as:

<html>
    <body>
        <script type="text/javascript">
            document.write("B.func1() return " + A.B.func());
        </script>
    </body>
</html>

And my java code is such as:

public class MyDemo extends Activity {
    private WebView mWebView;

    public void onCreate(Bundle savedInstanceState) {
        ...
        mWebView = (WebView)findViewById(R.id.webView1);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new AClass(), "A");
        mWebView.loadUrl("file:///android_asset/mydemo.html");
    }

    final class AClass {
        final class BClass {
            BClass() {}
            int func() { return 1; }
        }

        public BClass B = new BClass();

        AClass() {}
    }
}

But when I run my app on simulator it can't run on right 开发者_如何学运维way. And the LogCat send warning to me such as: TypeError : Result of expression 'A.B' [undefined] is not an object. at file:///android_asset/mydemo.html

So my question is:

1. if I want to bind javascript interface format as "A.B.func()" to my java class, how can I do it?

2. if I want to get javascript class's property directly, not by function calling, how can I do it? a javascript sample to show Q2 use "var prop = A.property" not use "var prop = A.getProperty()"

Expect your help! Thank you!


I don't think you can. You could just add methods in A, like b_doSomething(){B.doSomething()} to "forward" your calls, and call those from javascript.

As for accessing properties, I'm not sure it's possible, the Javascript Interface is made for calling methods (pretty much like a normal Java Interface, I guess).


Eclispe show message in LogCat "Uncaught TypeError: Object [object Object] has no method 'toast'". But in phone it works successfully...

<script>
    function doHemant() {
       jse.doThis();
    }
</script>

<input type="button" value="Toast" onClick="doHemant();" /> <br />

wv.addJavascriptInterface(new JavaScriptExtensions(), "jse");

class JavaScriptExtensions 
{ 
    public void doThis() 
    {
       Toast.makeText(MainActivity.this, "Wata Toast...", TOAST_LONG).show();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜