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 ??

221b
  • 431
  • 1
  • 11
  • 34

1 Answers1

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! :)

Community
  • 1
  • 1
diogo
  • 3,769
  • 1
  • 24
  • 30
  • 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 ? – 221b Dec 30 '16 at 10:28
  • Does it make a difference where I configure the addJavascriptInterface() ? – 221b Dec 30 '16 at 10:38
  • 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... – diogo Dec 30 '16 at 10:41
  • So for now - I changed my HTML/JS to match what the Android docs have - my HTML looks like : JavaScript: – 221b Dec 30 '16 at 11:08
  • 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: http://myurlhere (35) – 221b Dec 30 '16 at 11:16
  • Just curious - my WebAppInterface class is within my main class, so the showToast function is in a different class altogether, could that be a problem? – 221b Dec 30 '16 at 12:07
  • any advice sir? – 221b Jan 01 '17 at 17:13
  • Yeah, it's gonna be hard to talk through here, let's chat: http://chat.stackoverflow.com/rooms/132024/android-webview-issue – diogo Jan 01 '17 at 19:16