How to Get Return Value from JavaScript in Webview of Android

How to get return values from javascript to android as String?


  • API Level 19+ (KITKAT and above)

    webView.evaluateJavascript //JS value received on => ValueCallback<String>#onReceiveValue
  • Old versions

    loadUrl("javascript:...") //JS value received on => JavaScriptInterface#callback

==>

webView.getSettings().setJavaScriptEnabled(true);

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
webView.addJavascriptInterface(new JavaScriptInterface(), "javascriptinterface");

private void saveProcess(int position) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("javascript:process_save('" + position + "');",new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
// value is the result returned by the Javascript as JSON
// Receive newpid here
Log.d("JS",value);
}
});
} else {
webView.loadUrl("javascript:javascriptinterface.callback(process_save('" + position + "');");
}
}

private class JavaScriptInterface {
@JavascriptInterface
public void callback(String value) {
// Receive newpid here
}
}

Checkout this working test project, Hope that guide you to achieve your target.

How I can call javascript function and get the return value from javascript function

For API Level < 19 there are only workarounds of either using a JavascriptInterface (my preferred method, below) or else hijacking the OnJsAlert method and using the alert() dialog instead. That then means you can't use the alert() function for its intended purpose.

View:

WebView.addJavascriptInterface(new JsInterface(), "AndroidApp");
WebView.loadUrl("javascript:doStringToMyAndroid('This string from android')")

JsInterface:

public class JsInterface() {
@JavascriptInterface
void receiveString(String value) {
// String received from WebView
Log.d("MyApp", value);
}
}

Javascript:

function doStringToMyAndroid(stringFromAndroid){
var myJsString = "Hello World" + ;
// Call the JavascriptInterface instead of returning the value
window.AndroidApp.receiveString(myJsString);
}

But on API Level 19+, we now have the evaluateJavascript method:

WebView.evaluateJavascript("(function() { return getStringToMyAndroid('" + myJsString + "'); })();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
Log.d("LogName", s); // Returns the value from the function
}
});

How to run a Java Script function and get return in Android?

you could do like this

Js calls methods in C#

Configure the OnCreate method in the Activity :

var webview = FindViewById<WebView>(Resource.Id.webView1);
WebSettings settings = webview.Settings;
settings.JavaScriptEnabled = true;
// load the javascript interface method to call the foreground method
webView.AddJavascriptInterface(new MyJSInterface(this), "CSharp");
webview.SetWebViewClient(new WebViewClient());

Create a C# class :

class MyJSInterface : Java.Lang.Object
{
Context context;

public MyJSInterface (Context context)
{
this.context = context;
}

[JavascriptInterface]
[Export]
public void ShowToast (string msg)
{
Toast.MakeText(context, msg, ToastLength.Short).Show();
}
}

And then it's called in JS :

<button type="button" onClick="CSharp.ShowToast ('Call C#')">Call C#</button>

You can refer to this document:https://github.com/xamarin/recipes/tree/master/Recipes/android/controls/webview/call_csharp_from_javascript

C# calls a method in JS and gets the callback value

webView.EvaluateJavascript("javascript: callJS();", new EvaluateBack());

class EvaluateBack : Java.Lang.Object,IValueCallback
{

public void OnReceiveValue(Object value)
{

Toast.MakeText(Android.App.Application.Context, value.ToString(), ToastLength.Short).Show();// you will get the value "100"
}
}

in JS :

<script>
function callJS(){
return 100;
}
</script>

How we can execute a javascript function and get a return value in our android application?

you can use mWebView.loadUrl("javascript:checkName"); to call the method...

Then you can use addJavascriptInterface() to add a Java object to the Javascript environment. Have your Java script call a method on that Java object to supply its "return value".

EDIT1: Or you can use following hack:

Add this Client to your WebView:

final class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d("LogTag", message);
result.confirm();
return true;
}
}

Now in your java script call do:

webView.loadUrl("javascript:alert(functionThatReturnsSomething)");

Now in the onJsAlert call "message" will contain the returned value.

Edit2:

So it does not work if we call javascript method just after call to load the URL since the page loads take time. So I created a test program to test that...

Following is my html file (named test.html) store in the assets folder:

<html>
<head>
<script language="javascript">
function fieldsOnDelete(message) {
alert("i am called with " + message);
window.myjava.returnValue(message + " JIJO");
}
</script>
<title>iSales android</title>


</head>
<body></body>
</html>
</body>
</html>

Following is my java class that would get that i would add to java script as interface and it would receive the return value:

public class MyJS {

public void returnValue(String string){
Log.d(this.getClass().getSimpleName(), string);
}

}

And following is my activity class:

public class CheckWebView extends Activity {

private WebView webView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_web_view);
webView = (WebView) findViewById(R.id.webview);

webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onConsoleMessage(String message, int lineNumber,
String sourceID) {
super.onConsoleMessage(message, lineNumber, sourceID);
Log.d(this.getClass().getCanonicalName(), "message " + message
+ " :::line number " + lineNumber + " :::source id "
+ sourceID);
}

@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
// TODO Auto-generated method stub

onConsoleMessage(consoleMessage.message(),
consoleMessage.lineNumber(), consoleMessage.sourceId());

Log.d(this.getClass().getCanonicalName(), "message::::: "
+ consoleMessage.message());

return super.onConsoleMessage(consoleMessage);
}
});

webView.addJavascriptInterface(new MyJS(), "myjava");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setAllowFileAccess(true);

webView.loadUrl("file:///android_asset/test.html");

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_check_web_view, menu);
return true;
}

/* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
webView.loadUrl("javascript:fieldsOnDelete('name');");
return super.onOptionsItemSelected(item);
}

}

The key here is that there should be some time interval between the call to load html file from assets folder and the call to javascript:method. Here I am calling it from onOptionsItemSelected and it is working fine.. if I move the webView.loadUrl("javascript:fieldsOnDelete('name');"); to the end of the onCreate() method the it shows the error that it can not find fieldsOnDelete() method...

Hope it Helps...

EDIT3:

Replace following in your code

webView.loadUrl("javascript:alert(javascript:fieldsOnDelete())");

with

webView.loadUrl("javascript:alert(fieldsOnDelete())");

and try...

How to return Android's Alert return value to WebView with JavascriptInterface?

What if you call js function after user click the "OK" button. It's like :

alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
myWebView.loadUrl("javascript:resetAll();");
}
});


Related Topics



Leave a reply



Submit