简体   繁体   English

使用JavaScriptInterface返回页面元素

[英]Using JavaScriptInterface to return page elements

I have a simple WebViewClient class that should return all the <p> elements of the page I am currently on (in a webview) 我有一个简单的WebViewClient类,该类应返回我当前所在页面的所有<p>元素(在Webview中)

Here is the code 这是代码

public class SearchClient extends WebViewClient {

class MyJavaScriptInterface {
    @SuppressWarnings("unused")
    public void processHTML(String[] html) {
    Log.w("Length", String.valueOf(html.length));
        for(String s : html)
        {

            Log.w("Row", s.toString());
        }



    }
}


public SearchClient(WebView wv)
{
    wv.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
}

public void onPageFinished(WebView view, String url) {
    view.loadUrl("javascript:window.HTMLOUT.processHTML(document.getElementsByTagName('p'));");

}

} }

document.getElementsByTagName clearly is returning the elements because "Log.w" line in the processHTML function has over 100 strings ... but the for loop crashes. document.getElementsByTagName显然正在返回元素,因为processHTML函数中的“ Log.w”行具有100多个字符串...但是for循环崩溃。 Why is this?? 为什么是这样??

NodeList is a JavaScript class, but only a Java interface. NodeListJavaScript类,但仅是Java接口。 In JavaScript you should create a method that converts the list to and array of Strings then you can pass it into your JavaScriptInterface method. JavaScript您应该创建一个将列表转换为String数组的方法, 然后可以将其传递给JavaScriptInterface方法。

From this SO question a solution could be: 根据这个问题 ,解决方案可能是:

function toArray(obj) {
  var array = [];
  // iterate backwards ensuring that length is an UInt32
  for (var i = obj.length >>> 0; i--;) { 
  array[i] = obj[i];
  }
  return array;
} 

It is also possible this would work (from question in link above), but have not tested myself: 这也可能会起作用(来自上面链接中的问题),但尚未进行自我测试:

Array.prototype.slice.call(list,0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM