【问题标题】:Get value from DIV element从 DIV 元素中获取值
【发布时间】:2019-08-20 07:41:51
【问题描述】:

我想将 HTML 元素值传递给 Android 应用程序。我

我尝试使用以下代码检索该值:

document.getElementById(\"summary\").value --> giving null value
document.getElementById(\"summary\").innerHtml --> giving null value
document.getElementById(\"summary\").textContent --> giving null value 

我正在尝试实现 javascript MutationObserver。所以每当内容发生变化时,我可以立即将值传递给android java代码。

谁能帮帮我?

我使用了以下代码:

    myWebView = (WebView)this.findViewById(R.id.myWebView);
    myWebView.getSettings().setJavaScriptEnabled(true);


     myWebView.loadUrl("https://helloworld.com/details");

    myWebView.addJavascriptInterface(new JavaScriptInterface(this, myWebView), "MyHandler");
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        myWebView.setWebContentsDebuggingEnabled(true);
    }

    myWebView.evaluateJavascript("(function(){return document.getElementById(\"summary\").textContent})();",
            new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String html) {
                   Log.e("HTML Content",html);
                }
            });

这是我的 HTML 代码:

 <div class="well" id="summary" *ngIf="viewModel != null">
    <div class="SuccessSummary">{{viewModel.successSummary}}</div>
 </div>

【问题讨论】:

  • 你确定helloworld.com/details这个域包含这么多HTML代码吗?
  • helloworld 我只是举个例子,在HTML页面中有很多代码。但是我想要 SuccessSummary DIV 对我的 Android 应用程序的价值,这就是我的观点。此值经常更改
  • 在这种情况下,应将MyHandler 添加到网页中。只要值发生变化,该键就会向您发送响应
  • 这是我的 Javascript
  • 在上面的 JavaScirpt 中,MutationObserver 正在工作,但我只想获取 Summary 值需要为此找到方法

标签: javascript java android webview


【解决方案1】:

试试这个

myWebView.evaluateJavascript("(function(){return 
document.getElementById('summary').innerHTML})();",
        new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String html) {
               Log.e("HTML Content",html);
            }
        });

【讨论】:

  • 它也给出了空输出
猜你喜欢
  • 2016-02-10
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 2016-11-13
  • 1970-01-01
  • 2017-09-08
  • 1970-01-01
相关资源
最近更新 更多