3

I have defined some webview and I open some webpage on it

WebView wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("http://mypage.com/");

My question is how can I count the number of links in that webpage ?

my first idea was to parse the html code and to count the "href" string in that html, but this solution sound like a noob solution to me. Is there more intelligent way to do this ?

Lukap
  • 31,523
  • 64
  • 157
  • 244

2 Answers2

1

If you can edit the HTML I think you can do that with a simple javascript function that sends the count data back to Android. You can see an answer about that here

The function in Javascript to count links can be as simple as this:

<script type="text/javascript">
   function countLinks()
   {
      var all_a = document.getElementsByTagName("a");
      return all_a.length;
   }
</script>
Community
  • 1
  • 1
SERPRO
  • 10,015
  • 8
  • 46
  • 63
0

First declare a JavaScriptInterface in android code:

public class JavaScriptInterface {
   Context mContext;
   /** Instantiate the interface and set the context */
   JavaScriptInterface(Context c) {
       mContext = c;
   }
   /** Get number of links */
   public void getNumOfLinks(int numOfLinks) {
       // Use the count as you like
   }
}

Then add this interface to your webview, when you call it:

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android");

Finally in the HTML code get the number of links from DOM and pass it to the java code via the interface:

<script type="text/javascript">
   Android.getNumOfLinks(document.getElementsByTagName("a").length)
</script>
iniju
  • 1,084
  • 7
  • 11