Android WebView usage record

preface

Recently, I made a simple application and used some WebView related knowledge. Here is a summary.

  • Assign values to input boxes in WebView
  • Read the value in the WebView control
  • Methods of executing web pages in WebView
  • Inject a js code to assign a click method to a control
  • Read tables in WebView web pages

1, Assign and take values to input boxes

First, the method of loading web pages

	//Load initial page
    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface"})
    public void loadWebView() {
        mWebView.loadUrl(INDEX_URL); // INDEX_URL web page address
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true); //Allow js operation
        /*
        * Add an internal class: InJavaScriptLocalObj
        */
        mWebView.addJavascriptInterface(new IndexActivity.InJavaScriptLocalObj(), "java_obj");
        //Listening Connections 
        mWebView.setWebViewClient(new WebViewClient() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @SuppressLint("SetTextI18n")
            @Override
            public void onPageFinished(WebView view, String url) {
              //Execute after loading web page
            }
        });
    }

	//Inner class
    //Interface for receiving data
    public final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void showDescription(String str, String tag) {
            // str read data
            // Data from tag tag 
        }
    }

case Get the value of an input

1. code of web page

<input autofocus="" 
       onblur="return checkValue(this);" 
       onfocus="return holdOldValue(this);" 
       type="text" 
       id="system_capacity" 
       name="system_capacity" 
       value="4" 
       class="input" 
       title="Allowable Range: 0.05 to 500,000" 
       valtype="num" 
       minval="0.05"
       maxval="500000" 
       displayname="DC System Size"
       oldvalue="4">

2. execution method

From the above, the id of the input control is system_capacity Therefore, the data <input> <select> is the same operation, the value and assignment are the same, <span> is slightly different, mainly because all js operations are familiar with js operations.

 		//Get system_capacity value <input> <select> value of tag
        mWebView.loadUrl("javascript:window.java_obj.showDescription("
                + "document.getElementById('system_capacity').value"
                + ",\'system_capacity\'" +
                ");");

 		//Get the value of the maindesc value <span> tag
                mWebView.loadUrl("javascript:window.java_obj.showDescription("
                        + "document.getElementById('maindesc').innerHTML"
                        + ",\'maindesc\'" +
                        ");");

3. receive this value

	//Inner class
    //Interface for receiving data
    public final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void showDescription(String str, String tag) {
            // str read data
            // Data from tag tag 
            if(str.equals("system_capacity")){
                 Log.v("lanjiabin", "value=" + str + "  tag= " + tag);
            }
        }
    }

4. assignment

Assign a value to an input field, which is very simple Execution method:

String strJS = String.format("javascript:document.getElementById('system_capacity').value='%s';", city);
mWebView.evaluateJavascript(strJS, null); // null transmit listening method here

system_capacity is the id of input, and city is the value to be transferred in, that is, the value to be assigned to the input field

2, Execute methods in web pages

//Execute a click method with control id "go"
String js = String.format("javascript:document.getElementById('go').click();"); 

//Execute the "appnav ('systeminfo','right') method in the original web page
 String fo = String.format("javascript:appNav('systeminfo', 'right');"); 

mWebView.evaluateJavascript(js, null); // null transmit listening method here

3, Inject a js to add a click event for the control

For example, this web page code

<input autofocus="" 
       onblur="return checkValue(this);" 
       onfocus="return holdOldValue(this);" 
       type="text" 
       id="system_capacity" 
       name="system_capacity" 
       value="4" 
       class="input" 
       title="Allowable Range: 0.05 to 500,000" 
       valtype="num" 
       minval="0.05"
       maxval="500000" 
       displayname="DC System Size"
       oldvalue="4">

onblur="return checkValue(this);" It is a method executed after the input field loses focus, so as to execute a method to verify data. We android should not directly operate the web page by hand to lose focus and get focus. How should we execute this method? At the beginning, I did this. It was also effective. I lost focus and gained focus through code. Look at this method:

//Get focus
// 1.mWebView gets the focus
mWebView.requestFocus();  

// 2. the input field of the web page gets the focus
String js1 = String.format("javascript:document.getElementById('system_capacity').focus();"); 

// 3 Assign value to input

// 4.input loses focus
String js2 = String.format("javascript:document.getElementById('system_capacity').blur();");

//implement
mWebView.evaluateJavascript(js1, null);
mWebView.evaluateJavascript(js2, null);

In this way, it goes through a process of getting focus and losing focus. The method onblur="return checkValue(this);" It has also been successfully implemented, but this seems too abrupt. It is necessary to display the web page, and then get the focus and lose the focus. We should change our thinking: We should extract this method, add it as the onclick method of input, and then execute it. First, inject js to add the onclick method:

//Change the method in onblur to onclick method. Inject js
String j1 = "javascript:document.getElementById('system_capacity').onclick=function(){checkValue(this)};";

//Then execute the onclick method to execute the method to verify the data
String j2 = "javascript:document.getElementById('system_capacity').onclick();";

4, WebView reads table data in web pages

In fact, as long as you are familiar with js code, you can basically complete the operation of this web page. The idea is as follows: 1. write a js code function to read the table, that is, a js function to return the data of the table 2. inject this js code into webview<br / >3 Execute this js code and get the return value js complete method for reading tables:

 function getTableContent(){
        var mytable = document.getElementById("results1");
        var data = new String();
        for(var i=0,rows=mytable.rows.length; i<rows; i++){
            for(var j=0,cells=mytable.rows[i].cells.length; j<cells; j++){
                data = data+"_"+mytable.rows[i].cells[j].innerHTML;
            }
        }
        return data;
    }

results1 in the code is the id of the table. I have described it realistically here. You can also pass the table id through parameters. In the for loop, you can see that I use "\u" To connect the data in each table, or you can change it to your favorite symbol. Injection and execution in Android

//js code
String results1 = "javascript:" + "(function(){ var mytable = document.getElementById(\"results1\");\n" +
                "\n" +
                "        var data = new String();\n" +
                "\n" +
                "        for(var i=0,rows=mytable.rows.length; i<rows; i++){\n" +
                "\n" +
                "            for(var j=0,cells=mytable.rows[i].cells.length; j<cells; j++){\n" +
                "\n" +
                "                data = data+\"_\"+mytable.rows[i].cells[j].innerHTML;\n" +
                "\n" +
                "            }\n" +
                "\n" +
                "        }\n" +
                "\n" +
                "        return data;})()";

//Execute the method and get the return value
mWebView.evaluateJavascript(results1, new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
            // Here you can get the returned table data
            // The format of data is basically value_value_value connected one by one    
            // Then you can get each data through string interception and regular expression    
            }
        }
                            
                            
//Regular expression intercepts data
public String[] regPattern(String reg, String value) {
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(value);
        if (matcher.find()) {
            return matcher.group(1).split("_");
        } else {
            return null;
        }
    }
                            
 //Delay 2 seconds to execute
new Handler().postDelayed(new Runnable() {
                    public void run() {
                      //Execution method
                    }
                }, 2000);

How many setbacks will we encounter in programming? If you give up, there must be an oasis at the end of the desert.

Tags: Javascript

Posted by lily on Tue, 31 May 2022 12:57:34 +0530