【问题标题】:Android: How to check whether findElementById returns null in Webview?Android:如何在 Webview 中检查 findElementById 是否返回 null?
【发布时间】:2019-11-09 16:35:14
【问题描述】:

在下面的代码中,我通过以下方式访问元素“搜索字段” 按 ID 查找元素。但我不想设置一个值,而是想检查 findElementById 返回 null,就像在 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); 
           }
    }
} 

【问题讨论】:

    标签: javascript android webview


    【解决方案1】:

    你应该使用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 + ")");
                    }
                });
            }
        });
    

    它将返回 javascript 响应的字符串值,在本例中为“true”或“false”。

    【讨论】:

    • 完美!像魅力一样工作。
    【解决方案2】:

    您也许可以使用 jsoup 解决此问题。这可能是一本不错的读物:Damilola Omoyiwola https://link.medium.com/gRCrINRNt1

    的“Android 中 JSOUP 入门”

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-14
        • 2020-04-15
        • 1970-01-01
        • 1970-01-01
        • 2013-10-14
        • 2017-10-10
        • 1970-01-01
        相关资源
        最近更新 更多