从DIV元素获取值

3
我希望将一个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>

你确定 https://helloworld.com/details 这个域名包含这么多的HTML代码吗? - Manoj Perumarath
helloworld只是我举的例子,在HTML页面中有很多代码。但我想要SuccessSummary DIV的值传递到我的Android应用程序中,这就是我的意图。这个值经常会发生变化。 - Subramanian
在这种情况下,应该将MyHandler添加到网页。那个关键字会在值改变时向您发送响应。 - Manoj Perumarath
这是我的Javascript<script type="text/javascript"> /** * @return {string} */ function MyHandler(){ return document.getElementById('summary').innerHTML; } var mutationObserver = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.log(mutation); }); }); mutationObserver.observe(document.do, { attributes: true, characterData: true, childList: true, subtree: true, attributeOldValue: true, characterDataOldValue: true }); </script> - Subramanian
在上面的JavaScript中,MutationObserver正在工作,但我只想获取摘要值,需要找到方法。 - Subramanian
1个回答

1

试试这个

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

它还输出了空值。 - Subramanian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接