Getting started with Android and html-js interaction


Some H5 cool interfaces will be nested in the current app, and our app needs to interact with H5. Let’s see how to interact with H5.

Basic settings of WebView

The following are the basic settings of WebView

WebSettings setting = mWebView.getSettings();
setting.setJavaScriptCanOpenWindowsAutomatically(true);// Set JS to directly open a window, such as window. Open (), which is false by default
        setting.setJavaScriptEnabled(true);// Whether to allow JS execution. The default value is false. When true is set, it will remind you that XSS vulnerabilities may be caused
        setting.setSupportZoom(true);// Whether it can be scaled. The default value is true
        setting.setBuiltInZoomControls(false);// Whether to display the zoom button. The default is false
        setting.setUseWideViewPort(true);// Set this property to scale at any scale. Large view mode
        setting.setLoadWithOverviewMode(true);// Solve the problem of web page adaptation together with setusewideviewport (true)
        setting.setAppCacheEnabled(true);// Use cache
        setting.setDomStorageEnabled(true);//DOM Storage
        setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); // The picture is too big

Enable log

Turn on the log setting of printing web, and you can see the log information:

webview.setWebChromeClient(new WebChromeClient() {
            public boolean onConsoleMessage(ConsoleMessage cm) {
                Logutils. E (tag), "print web log ------" + cm. Message() + "-- from line"
                        + cm.lineNumber() + " of "
                        + cm.sourceId());
                return true;

Add JavaScript interface;

mWebView.addJavascriptInterface(new AndroidJavaScript(), "test");


public class AndroidJavaScript {
        public void testPage() {
            LogUtils.e("test", "testPage");

Testpage is the name agreed with H5. The above is the simple interaction between Android and JS. The specific details need to be discussed with H5.

HTML simple code

There are mainly two buttons and two JS methods

function AndroidCallJs(){
     document.getElementById("content").innerHTML =
         "< br \ > Android called the parameterless function of JS";

function AndroidCallJsParam(arg){
     document.getElementById("content").innerHTML =

HTML Test 

How to call Android

//Calling JS method without parameters  
//Calling HTML JS method with parameters
webview.loadUrl("javascript:AndroidCallJsParam(" + "''" + ")");

Welcome to the official account of the prince and the pig.