super5723 super5723 - 6 months ago 482
Android Question

Android webview activity,how to get js return value?

js code like this:
function a(){return "hello";}

in android webview activity, how to call js function a() get the return value "hello" ?

webview.addJavaInterface? webview.loadUrl()? i can`t get it.

please tell me how to solve the problem.

Answer

My advice would be:

1- Define a Javascript interface

A plain Java class with some methods and attributes, use annotation to expose the method you desire to the webview JS scope

public class MyInterface {

private WebView webView;

//pass the reference to the webview in your constructor
public JavascriptCallback(WebView webView) {
    this.webView = webView;
}

//expose this method to the JS scope using annotation
@JavascriptInterface
void sumNumbers(final String num1, final String num2, final String JScallbackFn) {
    this.javascriptCallback(JScallbackFn, num1 + num2);
}

//run the callback into the JS scope
void javascriptCallback(final String callback, final String result) {
    webView.post(new Runnable() {
        @Override
        public void run() { webView.load("javascript:"+callback+"("+result+")", null);
        }
    });
}

2- Inject the JavaScript interface in your webview

webview.addJavascriptInterface(new MyInterface(this.getActivity(), webview), "MyInterface");

3- Invoke the JS method (from within the webview)

MyInterface.sumNumbers(12, 34, showResult);

function showResult(res) {
    document.getElementById('myDiv').innerHTML(res);
}

For more extensive explanation about how webviews works on Android check the official documentation http://developer.android.com/guide/webapps/webview.html

Comments