super5723 super5723 - 4 months ago 228x
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.


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
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) { Runnable() {
        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) {

For more extensive explanation about how webviews works on Android check the official documentation