问题
I am new to Java and Android and I got a question. I think the solution is maybe very easy but I couldn't solve it.
I created an application with a WebView the thing is I want that the webview enters username and password automatically so that the user is already logged in when he starts the application. I googled it and found something like that but it does not work
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://euterpe.webuntis.com/WebUntis/index.do#main");
webView.setWebViewClient(new WebViewClient ());
class MyWebViewClient extends WebViewClient {
@Override
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
handler.proceed("Username", "password");
}
}
回答1:
hello please try this:
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("javascript:document.getElementsByName('school').value = 'schoolname'");
webView.loadUrl("javascript:document.getElementsByName('j_username').value = 'username'");
webView.loadUrl("javascript:document.getElementsByName('j_password').value = 'password'");
webView.loadUrl("javascript:document.forms['login'].submit()");
the first line enables javascript
all other lines fill in the form and eventually submit the form.
Look at the String apostrophes please i edited my answer.
回答2:
Though this is an old question I thought I would post my solution:
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://your.url");
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:document.getElementsByName('school')[0].value = 'schoolname'");
view.loadUrl("javascript:document.getElementsByName('j_username')[0].value = 'username'");
view.loadUrl("javascript:document.getElementsByName('j_password')[0].value = 'password'");
view.loadUrl("javascript:document.forms['login'].submit()");
}
});
It looks much alike the answer from Benjamin. Only difference is the [0] part, selecting the first found element, plus my implementation waits for the page to load before firering javascript at it.
回答3:
Replace
webView.setWebViewClient(new WebViewClient ());
with
webView.setWebViewClient(new MyWebViewClient ());
Only then the override method onReceivedHttpAuthRequest
will get called.
This handling will only work for HTTP authentication requests.
来源:https://stackoverflow.com/questions/16055800/how-to-enter-password-automatically-in-webview