Android: 如何在Webview中查看findElementById returns是否为null?

Android: How to check whether findElementById returns null in Webview?

在下面的代码中,我通过以下方式访问元素 'search-field' 通过 Id 查找元素。但我不想设置一个值,而是想检查 findElementById 是否 returns 空,如 Javascript:

if(document.getElementById('search field')==null).

我怎么能在这里做到这一点?

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_second);

     WebView wb = (WebView) findViewById(R.id.webView);
     String url = "https://www.leo.org/englisch-deutsch/";
     wb.loadUrl(url);

     wb.getSettings().setJavaScriptEnabled(true);
     wb.getSettings().setDomStorageEnabled(true);

     wb.setWebViewClient(new WebViewClient() {
           public void onPageFinished(WebView view, String url) {
               String s = "tea";
               String js = "javascript:(function() {document.getElementById('search-field').value = '"+s+"';})();";
               view.loadUrl(js); 
           }
    }
} 

您也许可以使用 jsoup 解决这个问题。这可能是一本好书:“Android 中的 JSOUP 入门”作者 Damilola Omoyiwola https://link.medium.com/gRCrINRNt1

您应该使用 evaluateJavascript 函数:

wb.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            String js2 = "var isNull = document.getElementById('search-field') == null; isNull;";
            view.evaluateJavascript(js2, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    Log.d("WebViewClient", "onReceiveValue(" + value + ")");
                }
            });
        }
    });

它将 return javascript 响应的字符串值,在本例中为 "true" 或 "false"。

只需检查字符串变量js是否为null或为空:

if (js.equals(null) || js.isEmpty()) {
   // do stuff when it's null or an empty string ...
}