How to get value from HTML field through webview using javascript?

0

I use WebView , I open the site normally, but I need to access it by passing a value from a given site field to TextView .

Is it 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;
            }
        });
    }
}
    
asked by anonymous 16.12.2015 / 02:28

1 answer

1

I have not worked for Android for some time, but I can use evaluateJavascript , similar to this answer , not I'm sure something has changed in the new Android APIs, but at the beginning 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");
        }
    }
});
    
16.12.2015 / 15:17