0

I'm trying to get simple values from two text boxes from my website on click of a button present there.

I followed this - https://developer.android.com/guide/webapps/webview.html#BindingJavaScript

to basically bind my client-side Android code to my JavaScript function on the website.

This is my Android code -

package course.org.webviewtesting;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * Created by User on 12/29/2016.
 */

public class WebViewTest extends Activity {

WebView mWebView;
ImageView logo;

@Override
public void onCreate(Bundle savedInstanceState) {

    final Activity mActivity = this;

    CookieSyncManager.createInstance(mActivity);
    CookieSyncManager.createInstance(getApplicationContext());
    CookieSyncManager.getInstance().sync();
    CookieManager.getInstance().setAcceptCookie(true);

    this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    logo = (ImageView) findViewById(R.id.logo);

    logo.setVisibility(View.VISIBLE); //logo as a loading screen
    // Makes Progress bar Visible
    getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);



    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.addJavascriptInterface(new WebAppInterface(this), "android");
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl("myURLhere");
    mWebView.setWebChromeClient(new WebChromeClient() {


        public void onProgressChanged(WebView view, int progress) {
            //Make the bar disappear after URL is loaded, and changes string to Loading...
            mActivity.setTitle("Loading...");
            mActivity.setProgress(progress * 100); //Make the bar disappear after URL is loaded

            if (progress == 100) {
                mActivity.setTitle(R.string.app_name);
                logo.setVisibility(View.GONE);
            }
        }


    });

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
        System.out.println(" url is " + url);

        }
    });

}

// this is from the Android Docs
public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showFields(String email, String name) {
        Toast.makeText(mContext, email+" "+name , Toast.LENGTH_SHORT).show();
        System.out.println("Email " + email + "Name - "+name);
    }
}

}

My HTML is as follows :

<input type="email" id="loginEmail" name="loginEmail" ng-model="loginEmail" ng-required="true" />

<input type="name" id="name" name="name" ng-model="name" ng-required="true" />

<button type="submit" class="btn btn-large" ng-click="showValues();" onClick="showValuesAndroid()">Check Values</button>

And the corresponding JavaScript :

<script type="text/javascript">
function showValuesAndroid() {
var a = document.getElementById("loginEmail").value;
var b = document.getElementById("name").value;
Android.showFields(a,b);
};
    </script>

My function gets the values in variables a and b, but I just can't seem to get the toast message on my WebView on click of the 'Check Values' button. Also - a System.out.println doesn't seem to be showing any values either.

Been stuck at this since almost 2 hours, what am I missing out/ doing wrong ??

6
  • 1
    Case sensitive "android" != "Android" Commented Dec 29, 2016 at 19:00
  • Are you sure that is the issue? Cause I took that from the docs and the two androids are different there as well. Commented Dec 29, 2016 at 19:07
  • Changed it to 'Android' but still don't see the toast Commented Dec 29, 2016 at 19:09
  • then its not a javascript error, tag it with java so that the java cracks have a look at it Commented Dec 29, 2016 at 19:10
  • by the way, why ng-click="showValues()"?? Commented Dec 29, 2016 at 19:10

1 Answer 1

2

The documentation is wrong, once JavaScript is case sensitive. If you pay attention to your Logcat, you'd probably see a message like:

com.androidbuts.sample I/chromium: [INFO:CONSOLE(XX)] "Uncaught ReferenceError: Android is not defined", source: ...

That's because the Android object is not properly set.

As @Jonas w stated, change the addJavascriptInterface() config to:

mWebView.addJavascriptInterface(new WebAppInterface(this), "Android");

... and it'll work fine! :)

Sign up to request clarification or add additional context in comments.

8 Comments

Ok - I did that, changed it to "Android". But I still see that error you mentioned in my logcat - is it not binding to my JavaScript function ?
Does it make a difference where I configure the addJavascriptInterface() ?
This error is the reason why the binding is not properly made. Also, WebView is too annoying when your HTML/JS is not following the right conventions. I tested your whole example and it's working fine with this correction. Please, update your post with the full HTML/JS you're using as well as with all the [INFO/ERROR:CONSOLE(XX)] Logcat messages you have. This way, we can try to track what's going on...
So for now - I changed my HTML/JS to match what the Android docs have - my HTML looks like : <input type="email" id="loginEmail" ng-model="loginEmail" ng-required="true" /> <button type="submit" ng-click="validateAndSubmit();" onClick="showAndroidToast('Hello Android!')">Check Values</button> JavaScript: <script type="text/javascript"> function showAndroidToast(toast) { Android.showToast(toast); }; Android: @JavascriptInterface public void showToast(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); }
The logcat error - 12-30 16:14:17.405 12042-12042/course.org.webviewtestI/chromium: [INFO:CONSOLE(35)] "Uncaught ReferenceError: Android is not defined", source: myurlhere (35)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.