Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get html element from my own web page from a WebView?

Tags:

android

I have a webview displaying a page from my own server. Is it possible to add a javascript method that would allow my android app to read out a page element from the webview? Something like:

// mypage.html
<html>
   <p id='abc'>some data</p>
</html>

// my android app
WebView wv = ..;
String data = wv.getPageElementById('abc');

Anything like that? I own the page so I can modify it however I need to make it work,

Thanks

like image 665
user291701 Avatar asked May 17 '11 17:05

user291701


1 Answers

Ok this is how i did it:

<html>

  <head> 
    <script type="text/javascript"> 

      function onBodyLoad() {
        var element = document.getElementById("abc");
        window.javascriptAccessor.getYerData(element.innerHTML); 
      }

    </script> 
  </head> 

  <body onload="onBodyLoad()">
    <div id="abc">data</p>
  </body>
</html>

Then my activity:

WebView webview = (WebView)findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new JavascriptAccessor(), "javascriptAccessor");
webview.setWebViewClient(new WebViewClient() {}); // wouldn't work without this!
webview.loadUrl(url);

private class JavascriptAccessor {
    @SuppressWarnings("unused")
    public void getYerData(String data) {
        Log.v(TAG, data);
    }
}

Yeah!

like image 111
user291701 Avatar answered Nov 03 '22 01:11

user291701