2

Is there any way to get access to DOM structure in Android's WebView? I need it to check if some DOM object exists on page and then fire some events.

Thank you!

vmg
  • 8,856
  • 12
  • 55
  • 83

2 Answers2

5

Not easily.

You can call loadUrl("javascript:..."), where the ... is a hunk of JavaScript code to be executed in the current Web page. If your "fire some events" are in the context of the Web page, perhaps this will suffice. If you need Java code to "fire some events", you will also need to use addJavaScriptInterface() to create a JavaScript->Java bridge object and have your loadUrl("javascript:...") code invoke it, to get your data back out into Java.

CommonsWare
  • 910,778
  • 176
  • 2,215
  • 2,253
  • @CrossleSong: That is not directly possible. However, you can use `addJavaScriptInterface()` to add a Java object as a synthetic JavaScript global, and have the JavaScript you pass to `loadUrl("javascript:...")` call methods on that global to deliver return values. – CommonsWare Jun 17 '13 at 10:28
3
   addJavascriptInterface(new WebviewJSInterface(), JS_INTERFACE);

   private class WebviewJSInterface
    {
        @JavascriptInterface
        public void processHTML(String output)
        {
            Log.d("log", "hello: " +output);
        }
    }

      @Override
        public void onPageFinished(WebView view, String url)
        {
            loadUrl("javascript:window. " + JS_INTERFACE + ".processHTML(document.getElementsByTagName('body')[0].innerHTML);");
            super.onPageFinished(view, url);
        }
Shilpi
  • 478
  • 1
  • 6
  • 12