Loading webpages using JavaScript in Android WebView / Executing JavaScript functions from Android

By | January 10, 2017

I think everyone has checked my previous post on how to improve Android WebView performance.

If not, check it here

Improve Android WebView Perfomance

Now we will see how we can load a webpage textfields with our custom values in Android WebView.

For this I am using a sample HTML file which is stored in my assets.

HTML file

My demo file is named “test.html”.

<form action="">
    First name: <input type="text" id="fname" name="fname"><br/><br/>
    Last name: <input type="text" name="lname"><br/><br/>
    coderzheaven.com
</form>

Below is the function that sets the values inside the textfields in the above HTML file.

String setTheFieldsInWebView(String fName, String secName) {
    return "document.getElementById('fname').value='" + fName + "'; " +
           "document.getElementsByName('lname')[0].value='" + secName + "';"; 
           // getElementsByName returns an array
}

MainActivity activity contains only a WebView that loads the above HTML file from the Android Assets folder.

MainActivity

package com.coderzheaven.webview_demo;

import android.graphics.Bitmap;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    static String url = "file:///android_asset/test.html";
    WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initWebView();
        setContentView(mWebView);
        setWebClients(setTheFieldsInWebView("Coderz", "Heaven"));
    }

    private void setWebClients(final String js) {
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                Toast.makeText(MainActivity.this, "Webpage Load Error", Toast.LENGTH_LONG).show();
                finish();
            }

            @Override
            public void onPageFinished(final WebView view, final String url) {
                super.onPageFinished(view, url);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    view.evaluateJavascript(js, new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String s) {
                            Log.i(TAG, "onReceiveValue: " + s);
                            mWebView.setVisibility(View.VISIBLE);
                        }
                    });
                } else {
                    view.loadUrl(js);
                    mWebView.setVisibility(View.VISIBLE);
                }


            }

        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                setTitle("Loading...");
                if (progress == 100)
                    setTitle(R.string.app_name);
            }
        });
    }

    void initWebView() {
        mWebView = new WebView(this);
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(false);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(false);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setDomStorageEnabled(true);
        mWebView.setVisibility(View.GONE);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.setScrollbarFadingEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        } else {
            mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        mWebView.setInitialScale(500);
        mWebView.loadUrl(url);
    }

    String setTheFieldsInWebView(String fName, String secName) {
        return "document.getElementById('fname').value='" + fName + "'; " +
                "document.getElementsByName('lname')[0].value='" + secName + "';"; 
                // getElementsByName returns an array
    }

}

Make easy money with infolinks

When the HTML file loading is finished the below code will evaluate the Javascript and populate the textfields in the file.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
	view.evaluateJavascript(js, new ValueCallback<String>() {
		@Override
		public void onReceiveValue(String s) {
			Log.i(TAG, "onReceiveValue: " + s);
			mWebView.setVisibility(View.VISIBLE);
		}
	});
} else {
	view.loadUrl(js);
	mWebView.setVisibility(View.VISIBLE);
}

All Done.

Please send your comments to coderzheaven@gmail.com.

Leave a Reply

Your email address will not be published. Required fields are marked *