How to get HTML field value through webview using javascript?

Asked

Viewed 862 times

0

Utilise WebView, open the site normally, but need that when accessing, it pass a value of a given field of the site to a TextView.

It is possible to do this ?

Follow the code below:

public class Inicio extends AppCompatActivity {

    TextView recuperarvalor;
    WebView site;

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

        recuperarvalor = (TextView) findViewById(R.id.idtextview);
        site = (WebView) findViewById(R.id.idwebview);

        site.loadUrl("https://nomedosite");

        WebSettings settings = site.getSettings();

        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.supportZoom();
        settings.setBuiltInZoomControls(true);

        settings.setTextZoom(150);
        settings.setSupportZoom(true);
        settings.setDomStorageEnabled(true);

        site.loadUrl("javascript:var x = document.getElementById('live_bid');");
        site.setWebViewClient(new WebViewClient() {
            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                site.loadUrl("javascript:var x = document.getElementById('live_bid');");

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }
}
  • hello! how do you open the site? Can show the code? it gets easier to help!

  • I updated with the code above.

1 answer

1

For some time I do not work with Android, but can use the evaluateJavascript, similar to this answer, I’m not sure if anything has changed in the new Android Apis, but at first this is it:

recuperarvalor = (TextView) findViewById(R.id.idtextview);

WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);

String executaScript = "var np = document.getElementById('live_bid');"+
        "if(np){"+ //Verifica se o campo existe
        "   return np.value;"+
        "} else {"+
        "   return false;"+//retorna false
        "}";

webView.evaluateJavascript(executaScript, new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String valor) {
        Log.d("LogName", valor);//Exibe o valor do input
        recuperarvalor.setText(valor);//Adiciona o valor no TextView
    }

    @Override
    public void onReceiveValue(boolean s) {
        if(s == false){
            Log.d("LogName", "Campo não encontrado");
        }
    }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.