【发布时间】:2016-11-22 09:02:14
【问题描述】:
我想在 WebView 中打开一个网页,并在页面加载后自动单击一个按钮。这是我目前的WebView 班级:
public class WebViewFragment extends Fragment {
...
@Override
public void onResume() {
super.onResume();
openUrl();
}
private void openUrl() {
setCookies();
if (urlToOpen != null) {
//tell webview to handle redirects (by default browser launches on redirects)
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (getActivity() != null)
((MainActivity) getActivity()).onShowLoading();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (getActivity() != null) {
executeJS();
((MainActivity) getActivity()).onHideLoading();
}
}
});
if (javascriptToExecute != null) {
webview.getSettings().setJavaScriptEnabled(true);
}
webview.loadUrl(urlToOpen);
}
}
private void executeJS() {
System.out.println("executeJS(): " + javascriptToExecute);
webview.loadUrl(javascriptToExecute);
}
}
我可以使用"javascript:$('#customer-info-edit').click();" 或"javascript:document.getElementById('customer-info-edit').click();" 都可以正常工作。
但问题是它们只能工作一次。如果我第一次打开 WebView,则会单击该按钮。但是,如果我按下物理后退按钮并再次打开 WebView,则不会单击该按钮。为什么 Javascript 不是每次都能正常工作?
【问题讨论】:
-
在浏览器中,后退按钮会触发从缓存中重新加载,这不会触发页面加载,而是将其重新加载到之前的状态。我从来没有使用过 webview,所以我不能说这是否是同一个问题,但这个链接会给你一些尝试的选项。只需将相关脚本直接放入您的页面中...stackoverflow.com/questions/15791148/…
标签: javascript android jquery webview