Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get return value from javascript in WebView of Android?

Tags:

android

return

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?

like image 494
Cuong Ta Avatar asked Jul 21 '10 11:07

Cuong Ta


People also ask

How to get data from WebView in Android?

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) .

How to call js function from Android?

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“).

What is JavaScript WebView?

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.

How do you communicate between WebView and native Android?

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.


2 Answers

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)

like image 145
Kirill Kulakov Avatar answered Oct 31 '22 04:10

Kirill Kulakov


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.

like image 64
Felix Khazin Avatar answered Oct 31 '22 05:10

Felix Khazin