0

I have a webview. I want to call JS function from Java and assign return value to a variable.

This line from java calls getUserDetails() function of JavaScript.

webview.loadUrl("javascript:window.getUserDetails()");

This is the getUserDetails function in javascript which returns a string

window.getUserDetails = function(){
    return "username"; 
}

I want to achieve something like this.

String user = webview.loadUrl("javascript:window.getUserDetails()");

How can I able to achieve this?

kiran puppala
  • 689
  • 8
  • 17

2 Answers2

0

You have to change the way you are calling that method.

webview.loadUrl("javascript:alert(window.getUserDetails())");

and while handling the alert your returned value will be there. For more info please follow this link

As per the comment you can do this in following way.

String  mUserName; 


String getUserName(){ 


runOnUiThread(new Runnable() {

        @Override
        public void run() {


webView.loadUrl("javascript:android.onData(window.getUserDetails())");

        }
    });

return mUserName;
}


@JavascriptInterface
public void onData(String value) {
   mUserName = value;
}
vinay kant
  • 66
  • 4
  • But I want to return that value instantly. I will use that line inside some function like this public String getUser(){ String user = webview.loadUrl("javascript:window.getUserDetails()"); return user; } – kiran puppala Jan 02 '19 at 12:12
  • @kiranpuppala, check out the new edit and see if thats what you are looking for? – vinay kant Jan 02 '19 at 14:21
  • But by the time mUserName gets returned, it wouldn't get initialized right. It will get initialized later in onData function. – kiran puppala Jan 03 '19 at 11:31
  • Yup, so when you call `webView.loadUrl("javascript:android.onData(window.getUserDetails())");` it in return call onData method and then you will have mUserName field initialised and the returned value will have correct userName. – vinay kant Jan 03 '19 at 12:02
  • Can you read my comment properly. `getUserName()` function will not wait until `mUserName` gets initialized. It just calls `webView.loadUrl("javascript:android.onData(window.getUserDetails())");` and returns null value of `mUserName` immediately. – kiran puppala Jan 05 '19 at 07:02
  • then do this `runOnUiThread(new Runnable() { @Override public void run() { webView.loadUrl("javascript:android.onData(window.getUserDetails())"); } });` – vinay kant Jan 05 '19 at 07:55
0

WebView#evaluateJavascript is the recommended way to do this asynchronously. If you want something which feels synchronous, you can try using Futures to wait for the callback:

final SettableFuture<String> jsFuture = SettableFuture<>.create();
webView.evaluateJavaScript("window.getUserDetails()", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String value) {
        jsFuture.set(value);
    }
});
String value = jsFuture.get();
nfischer
  • 181
  • 3