7

evaluatejavascript is available API-level 19 and later. It has a callback. I know that I can use loadUrl instead of evaluatejavascript for before API-level 19. But how can I handle return value from script? Is there a solution for this?

String script = "function(){ return "abc"}()";
mywebview.loadUrl(script);
Anil
  • 1,605
  • 1
  • 14
  • 24

1 Answers1

0

You can use WebView.addJavascriptInterface() for this. Then the JavaScript can use the interface to communicate back to your code.

Example code:

class JsObject {
    @JavascriptInterface
    public void returnValue(String value){
        Log.d("JsObject", "Got value [" + value + "]");
    }
}
mywebview.getSettings().setJavaScriptEnabled(true);
mywebview.addJavascriptInterface(new JsObject(), "injectedObject");
mywebview.loadUrl("javascript:function(){ injectedObject.returnValue('abc')}()");
Roy Solberg
  • 18,133
  • 12
  • 49
  • 76