Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve HTML content from WebView (as a string)

How do I retrieve all HTML content currently displayed in a WebView?

I found WebView.loadData() but I couldn't find the opposite equivalent (e.g. WebView.getData())

Please note that I am interested in retrieving that data for web pages that I have no control over (i.e. I cannot inject a Javascript function into those pages, so that that it would call a Javascript interface in WebView).

like image 388
JohnK Avatar asked Mar 10 '11 18:03

JohnK


People also ask

How do I display HTML content in WebView?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken web view to show html content.

Which method is used to load HTML content in WebView?

The loadUrl() and loadData() methods of Android WebView class are used to load and display web page.

How can I get HTML code from URL in android?

Android phone or tablet using Chrome Open the Google Chrome browser on your Android phone or tablet. Open the web page whose source code you want to view. Tap once in the address bar and move the cursor to the front of the URL. Type view-source: and tap Enter or Go.


2 Answers

You can achieve this through:

final Context myApp = this;  /* An instance of this class will be registered as a JavaScript interface */ class MyJavaScriptInterface {     @SuppressWarnings("unused")     public void processHTML(String html)     {         // process the html as needed by the app     } }  final WebView browser = (WebView)findViewById(R.id.browser); /* JavaScript must be enabled if you want it to work, obviously */ browser.getSettings().setJavaScriptEnabled(true);  /* Register a new JavaScript interface called HTMLOUT */ browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");  /* WebViewClient must be set BEFORE calling loadUrl! */ browser.setWebViewClient(new WebViewClient() {     @Override     public void onPageFinished(WebView view, String url)     {         /* This call inject JavaScript into the page which just finished loading. */         browser.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");     } });  /* load a web page */ browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html"); 

You will get the whole Html contnet in processHTML method. and it wont make another request for webpage. so it is also more efficient way for doing this.

Thanks.

like image 62
Shridutt Kothari Avatar answered Oct 05 '22 07:10

Shridutt Kothari


Unfortunately there is not easy way to do this.

See How do I get the web page contents from a WebView?

You could just make a HttpRequest to the same page as your WebView and get the response.

like image 31
brendan Avatar answered Oct 05 '22 07:10

brendan