How to check in Android WebView if login failed or successful? The login webpage shows following message when login fails due to incorrect username and/or password.
<div id="errorMsgId1427032461760" class="errorMessage">
How to check this using JavaScript? (calling next activity works but it always calls next activity. So I want to run this check).
EDIT: I tried by adding JavaScript Interface to webView.loadURL() but it didn't work.
webView.loadUrl("javascript: if(document.body.innerHTML.toString().indexOf('Invalid') > -1){\n" +
" JSInterface.changeActivity() ;");
EDIT 2: How to use this?
if(document.body.innerHTML.toString().indexOf("invalid") > -1){ alert("invalid'");
and then call Intent if alert isn't called. (Alert can be any function).
EDIT 3:
I tried with onConsoleMessage, but it doesn't work. Here's code:
webView.setWebChromeClient(new WebChromeClient() {@
Override
public boolean onConsoleMessage(ConsoleMessage cm) {
String a = cm.toString();
if (a.equalsIgnoreCase("Success")) {
Toast.makeText(Login.this, "Login Successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Login.this, Upload.class);
Login.this.finish();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
if (a.equalsIgnoreCase("Error")) {
Toast.makeText(Login.this, "Please enter correct credentials", Toast.LENGTH_LONG).show();
}
return true;
}
});
and in onPageFinished method as:
webView.setWebViewClient(new WebViewClient() {
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onPageFinished(WebView view, final String url) {
webView.loadUrl("javascript: if (document.querySelectorAll('[type=submit]').length) {\n" +
" var x = document.querySelectorAll('[type=submit]');\n" +
" x[0].addEventListener(\"click\", function() {\n" +
" if (document.body.innerHTML.toString().indexOf(\"Invalid\") > -1) console.log(\"Error\");\n" +
" else console.log(\"Success\");\n" +
" });};");
return true;
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://192.168.0.101:9999/user"); //Local URL.
I checked above Javascript with alert instead of console.log and it works.
What's error? I can't figure it out.