I want to get a return value from Javascript in Android. I can do it with the iPhone, but I can't with Android. I used loadUrl, but it returned void instead of an object. Can anybody help me?
Depending on your requirements, you can fetch the contents of the WebView from the web using webView. loadUrl("<url>") method, or you can bind the code directly (e.g. after loading it from assets) using webView. loadDataWithBaseURL("", html, "text/html", "UTF-8", null) .
WebView allows you to bind JavaScript code to Android code through an interface. To do this, we must use the addJavaScriptInterface() method, which is passed the class that provides the interface for JS, and the name that will be used to display the instance in JS (for example, “AndroidFunction“).
Web view acts as an in-built browser which displays the webpages in Android. In other words, Web view turns your application into web application. WebView is an extension of Android's View class. It uses WebKit to display a web page which is a browser engine which provides tools for browsing the web.
2 — Android: 2.1 To receive data from webview ,we can create an interface, which will enable webview to connect the native layer and pass data. From native layer, create a class and replicate the following. While configuring web view, we need to set JavaScript interface as above JSBridge class.
Same as Keith
but shorter answer
webView.addJavascriptInterface(this, "android");
webView.loadUrl("javascript:android.onData(functionThatReturnsSomething)");
And implement the function
@JavascriptInterface
public void onData(String value) {
//.. do something with the data
}
Don't forget to remove the onData
from proguard
list (if you have enabled proguard)
Here's a hack on how you can accomplish it:
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 javascript call do:
webView.loadUrl("javascript:alert(functionThatReturnsSomething)");
Now in the onJsAlert call "message" will contain the returned value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With