我的网页视图包含以下设置:
mView.getSettings().setLoadWithOverviewMode(true);
mView.getSettings().setUseWideViewPort(false);
mView.getSettings().setJavaScriptEnabled(true);
mView.getSettings().setAllowContentAccess(true);
mView.getSettings().setDomStorageEnabled(true);
加载网页后,当我尝试执行Javascript时:
mView.loadUrl("javascript:document.querySelector('input[type=password]').value ='" + password + "'");
打开新标签或窗口,而不是设置密码字段的值。
document.querySelector('input[type=password]')
的输出(来自控制台):
<input type="password" name="userpassword" id="userpassword" maxlength="6" style="width: 128px; height: 18px">
我尝试从控制台执行相同的JavaScript。它有效!
我还配置了webviewclient:
mView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d(TAG, " shouldOverrideUrlLoading :" + url);
view.loadUrl(url);
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d(TAG, "onPageStarted " + url);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
}
});
答案 0 :(得分:1)
loadUrl
方法,在WebView中加载提供的URL。您需要做的是执行evaluateJavascript
方法。
webView.evaluateJavascript("document.querySelector('input[type=password]').value ='" + password + "'", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
/// This callback is called after a result is returned by the script.
}
});
答案 1 :(得分:1)
自Android Kitkat(4.4,API级别19)起,您可以使用evaluateJavascript
。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("js_code", null);
} else {
webView.loadUrl("javascript:js_code");
}
答案 2 :(得分:0)