Fill Form Programmatically In Android Webview - Javascript
Solution 1:
This is untested, but I see two things wrong here:
You should call
setWebViewClient
with yourWebViewClient
implementation before you callloadUrl
. However,loadUrl
is asynchronous, so it probably would not make a difference, but this is worth a try I think.You are not calling
super.onPageFinished(view, url);
in onPageFinshed. You should add this call.
EDIT 2:
I finally took a look at the actual page you are working with. The problem is that the page loads content in a different frame, so you actually have to make the getElementsByName
call on a different document. The frame in which both of the inputs you want are located has the name mainFrame
in your page. So, you should write the javascript like this and load that into the WebView
as you have done above:
window.frames["mainFrame"].document.
getElementsByName('p_codigo_c')[0].value = "user";
window.frames["mainFrame"].document.
getElementsByName('p_clave_c')[0].value = "password";
Solution 2:
this works for me for API version greater than 18
mWebView = findViewById(R.id.web_view);
String url = "https://duckduckgo.com";
mWebView.loadUrl(url);
mWebView.getSettings().setJavaScriptEnabled(true);
final String js = "javascript:document.getElementById('search_form_input_homepage').value='android';" +
"document.getElementById('search_button_homepage').click()";
mWebView.setWebViewClient(newWebViewClient(){
publicvoidonPageFinished(WebView view, String url){
if(Build.VERSION.SDK_INT >= 19){
view.evaluateJavascript(js, newValueCallback<String>() {
@OverridepublicvoidonReceiveValue(String s) {
}
});
}
}
});
here important is view.evaluateJavascript
Solution 3:
You just need to enable domelements
myview.getSettings().setDomStorageEnabled(true);
and then use getelementby id like
javascript:var x = document.getElementById('myfield').value = 'aaa';
and do this in
onPageFinishedLoading(){}
got this from the link Android WebView always returns null for javascript getElementById on loadUrl
Solution 4:
For me, it is required to fill multiple entries in form one by one on callback of each "webView.evaluateJavascript" Note: API version > 18
See below snippet for reference
ArrayList<String> arr = newArrayList<String>();
arr.add("document.getElementsByName(\"tag_name\")[0].value = \"your_value\";");
.
.
.
call setValue(arr, 0)
privatevoidsetValue(final ArrayList<String> arr, final int i) {
if (i < arr.size()) {
webView.evaluateJavascript(arr.get(i), newValueCallback<String>() {
@OverridepublicvoidonReceiveValue(String value) {
int j = i + 1;
setValue(arr, j);
}
});
}else{
webView.evaluateJavascript("document.getElementById(\"your_form_id\").submit();", newValueCallback<String>() {
@OverridepublicvoidonReceiveValue(String value) {
Toast.makeText(MainActivity.this, "Submitted: "+value, Toast.LENGTH_SHORT).show();
}
});
}
}
Post a Comment for "Fill Form Programmatically In Android Webview - Javascript"