4

I have an android application in which I have a webview. How can I when I press the back button on android I can delete a character in the text area of ​​webview?

package com.example.nqc.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = findViewById(R.id.mWebView);
        mWebView.loadUrl("https://www.google.com");
    }

    @Override
    public void onBackPressed() {
        //delete a character
        Log.d("Debug", "Delete text on TextArea");
    }
}

Please see the picture below if you do not understand what I said.

Before press back

After press back

xPain
  • 132
  • 10
NQC
  • 43
  • 5
  • Do you mean: To back to previous page with previous text that was in the search box? – Yahya Jul 03 '18 at 09:48
  • No, I mean: press the back button > delete a character (e) in textArea (search box) instead of back to previous page. (This is like pressing the delete button on the soft keyboard) – NQC Jul 03 '18 at 10:08
  • What if you have a page other than *google.com* , Do you want the same behavior? ... Because according to your comment , the *back* button will work as a single-char deleter.... Can you elaborate why exactly you want to achieve this? – Yahya Jul 03 '18 at 10:15
  • This will happen to all other pages. I need to press the back button on the **remote control** in an android tv application. It is similar to what I described above – NQC Jul 03 '18 at 10:27

1 Answers1

3

There is no guarantee that there will be only one Form in the page the user has loaded.

However, if it's for the Google Search Form in particular, you can then execute a JavaScript to get a Form in the Google.com page that has id=tsf (which is the unique id of the search form in Google.com).

Nevertheless, you mentioned in your comment:

This will happen to all other pages

Unless you know the id of the form in the page (which is practically impossible for every page in WWW that contains more than one Form). You can loop through all Forms and remove the last char of the text in the Form's input of type text.


Example

First create a method to run the JS script (note that there are different ways to execute a JS in WebView in Android, for more details in case the following method did not work for you, look here):

public void run(final String script) { 
      mWebView.post(new Runnable() {
          @Override
          public void run() { 
              mWebView.loadUrl("javascript:" + script); 
          }
      }); 
}

Then create a method that returns a JS String to:

  1. Get all Forms in the page.
  2. Cycle through them all.
  3. Cycle through the elements of each Form..
  4. Set its value to (its old value - last char).

private String deleteLastCharScript() {
    return  "var listOfForms = document.forms;\n" + 
            "for(var i = 0; i < listOfForms.length; i++) {\n" + 
            "   var elements = listOfForms[i].elements;\n" +
            "   for(var j = 0 ; j < elements.length ; j++){\n" +
            "       var item = elements.item(j);\n" +
            "       item.value = item.value.substring(0, item.value.length - 1);\n" + 
            "   }\n" + 
            "};";       
}

You can run that script in the onBackPressed() method like this:

@Override
public void onBackPressed() {
    run(deleteLastCharScript());
}

This is MCVE:

Add to Manifest:

<uses-permission android:name="android.permission.INTERNET" />

Create Simple WebView Layout:

<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

Implementation in Activity:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        mWebView = findViewById(R.id.webView1);
        mWebView.getSettings().setJavaScriptEnabled(true); // enable JS
        mWebView.loadUrl("https://www.google.com");
    }

    /**
     * Execute JS String Asynchronously
     * @param script
     */
    public void run(final String script) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            // run JavaScript asynchronously
            // it works on KitKat onwards
            mWebView.evaluateJavascript(script, null);
        }else {
            // use different thread to run JavaScript asynchronously
            // because evaluateJavascript doesn't work on versions before KitKat
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mWebView.post(new Runnable() {
                        @Override
                        public void run() {
                          mWebView.loadUrl("javascript:" + script);
                        }
                    });
                }
            }).start();
        }
    }


    /**
     * This JS Script tp Loop through all
     * inputs in all forms in the page
     * and remove last char from each
     * @return
     */
    private String deleteLastCharScript() {
        return  "var listOfForms = document.forms;\n" +
                "for(var i = 0; i < listOfForms.length; i++) {\n" +
                "   var elements = listOfForms[i].elements;\n" +
                "   for(var j = 0 ; j < elements.length ; j++){\n" +
                "       var item = elements.item(j);\n" +
                "       item.value = item.value.substring(0, item.value.length - 1);\n" +
                "   }\n" +
                "};";
    }


    @Override
    public void onBackPressed() {
        run(deleteLastCharScript());
    }
}

Result

Test

Community
  • 1
  • 1
Yahya
  • 9,370
  • 4
  • 26
  • 43