There's no straightforward way to do what you want, though it can be done. First, define an interface that goes something like:
public interface WebInterfaceDelegate {
public void receivedHtml(String html);
}
Then, define a class that you want to expose to the JavaScript runtime in your WebView, something along the lines of:
public static class WebViewJavaScriptInterface {
private WebInterfaceDelegate delegate;
public WebViewJavaScriptInterface(WebInterfaceDelegate delegate) {
this.delegate = delegate;
}
public void htmlLoaded(String html) {
if (delegate != null) {
delegate.receivedHtml(html);
}
}
}
Then, make your Activity
implement the interface you defined above, like:
public class AndroidWebViewActivity extends Activity implements WebInterfaceDelegate {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
WebView webView = (WebView)findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewJavaScriptInterface(this), "AndroidAPI");
webView.loadUrl("http://your.url.com");
}
//...
public void receivedHtml(String html) {
//inspect the HTML here
System.out.println("Got html: " + html);
}
}
Finally, add some JavaScript to your page that goes like:
<script>
window.onload = function() {
AndroidAPI.htmlLoaded(document.body.innerHTML);
}
</script>
So you can do all that, or you can just use something like URL.openStream()
to connect directly to your target webpage and read the markup off of the socket instead of off of the WebView
. To do this is as simple as:
InputStream response = new URL("http://example.com/mypage.php").openStream();
//read the data from the response into a buffer, then inspect the buffer
You can find some additional information here:
http://docs.oracle.com/javase/6/docs/api/java/net/URL.html