javascriptandroidwebviewhtml-parsingcode-injection

Is it possible to get data from HTML forms into android while using webView?


I'm making a very simple form in HTML which is viewed in android using the webview which takes in your name using a textbox and when you click on the button, it displays it into a paragraph and it's made using both html and javascript. This is my html code:

<!DOCTYPE html>
<html>
<body>
<p> Write your name and win your favorite game console name and win it! The winners will be announced in 4 days.</p>
Type your name here: <input id="thebox" type="text" name="value" value=""><br>

    <button onclick="myFunction()">Try it</button>

    <p id="demo"></p>

    <script>
    function myFunction() {
        var x = document.getElementById("thebox").value;
        document.getElementById("demo").innerHTML = x;
    }
    </script>

    </body>
    </html>

NEW EDITED FORM

<form name="albert" action="" method="POST">

 <label for="firstname"> First Name </label>
 <br /><br />

 <input type="text" name="firstname" id="firstname" />

 <input type="submit" name="sbumit" value="Submit" />


</form>

I want to get the value from the input box called "thebox" in a variable in android on the button click and I tried lots of stuff before and I followed a method where you inject a JS file but since I know nothing about JS so I did fail trying that and here is the file that I put in my project and the file is called inject.js:

document.getElementsByTagName('form')[0].onsubmit = function () {
    var objPWD, objAccount, objSave;
    var str = '';
    var inputs = document.getElementsByTagName('thebox');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].name.toLowerCase() === 'thebox') {
            objAccount = inputs[i];
        }
    }
    if(objAccount != null) {
        str += objAccount.value;
    }
    if(objPWD != null) {
        str += ' , ' + objPWD.value;
    }
    if(objSave != null) {
        str += ' , ' + objSave.value;
    }
    window.AndroidInterface.processHTML(str);
    return true;
};

And later as I followed that article it said that I need to put some stuff in my MainActivity but since I'm using webview for the first time, I couldn't understand much and heres the code I put into my MainActivity:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WebView webView = new WebView(this);
        this.setContentView(webView);

        // enable javascript
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(), "AndroidInterface");

        // catch events
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                try {
                    view.loadUrl("javascript:" + buildInjection());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        webView.loadUrl("http://someurl.com");
    }

A nested class that I made in my MainActivity:

class JavaScriptInterface {
        @JavascriptInterface
        public void processHTML(String formData) {
            Log.d("AWESOME_TAG", "form data: " + formData);
        }
    }

And finally the method that injects the code:

private String buildInjection() throws IOException {
        StringBuilder buf = new StringBuilder();
        InputStream inject = getAssets().open("inject.js");// file from assets
        BufferedReader in = new BufferedReader(new InputStreamReader(inject, "UTF-8"));
        String str;
        while ((str = in.readLine()) != null) {
            buf.append(str);
        }
        in.close();

        return buf.toString();
    }

I want to get value from the html form(the-input-box) that I show in a webview in Android and is it really possible to do that and if yes how and please explain? Thanks and also please tell in what variable will I get the value.


Solution

  •     Webview browser=(WebView)view.findViewById(R.id.webChart);
        browser.getSettings().setJavaScriptEnabled(true);
        browser.addJavascriptInterface(new WebAppInterface(getActivity()), "Android");
        browser.loadUrl("file:///android_asset/yourHtmlFileName.html");
    

    add this interface class, WebAppInterface

    public class WebAppInterface {
     Context mContext;
     String data;
    
     WebAppInterface(Context ctx){
        this.mContext=ctx;
     } 
    
    
     @JavascriptInterface
     public void sendData(String data) {
        //Get the string value to process
          this.data=data;
     }
    }
    

    your HTML code data

     function loadChartData() {
      var x = document.getElementById("thebox").value;
       Android.sendData(x);
     }
    

    call this function when the html button click in android webview

    UPDATE

    1) By default javascript is disabled in webview . to enable it, get the settings of the webview and call the setJavaScriptEnabled(true); to true.

    2) to create the interface between your Javascript code and your android code, you need to create Javacript interface class.

    3) bind the interface between your javascript code to android code, you need to pass the reference of the interface class and an interface name that your javaScript can call to access the class.

    4) pass the html file path to load into the webview(browser).

    5) create the interface class like below(WebAppInterface).

    see this link for more details https://developer.android.com/guide/webapps/webview.html

    6) in HTML file, create the button and add the click listener to that button and call the sendData("your value") function with interface name(Here Android).

    Thats all. you can pass the value from html to your android code.