Skip to content

Instantly share code, notes, and snippets.

@medhdj
Created February 2, 2015 17:55
Show Gist options
  • Save medhdj/4a6485b07034f4de88dc to your computer and use it in GitHub Desktop.
Save medhdj/4a6485b07034f4de88dc to your computer and use it in GitHub Desktop.
package com.example.android.customchoicelist;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebActivity extends Activity {
WebView myBrowser;
String urlToBrowse = "http://www.google.com/";
String htmlCode = null;
StringBuffer buffer = new StringBuffer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
myBrowser = (WebView) findViewById(R.id.webview1);
// Browser settings
WebSettings myBrowserSettings = myBrowser.getSettings();
// Prevent cache to be used
myBrowserSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
myBrowserSettings.setAppCacheEnabled(false);
// General settings
Log.d("Stefano", "JS enabled");
// FIREFOX user agent
myBrowserSettings
.setUserAgentString("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
myBrowser.setWebChromeClient(new WebChromeClient());
myBrowser.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
WebSettings myBrowserSettings = myBrowser.getSettings();
myBrowserSettings.setJavaScriptEnabled(true);
Log.d("Stefano", "JS enabled");
Log.d("Stefano", "OnPageFinished running");
Log.d("Stefano", "js enabled "+myBrowserSettings.getJavaScriptEnabled());
}
});
// Start the delayed HTML code extraction
delayedStartHtmlExtractor(16000);
//delayedStartHtmlExtractor(16000);
Log.d("Stefano", "DelayedStart HTML Extractor launched");
// Prepare Javascript to extract the HTML code from the webview
myBrowser.addJavascriptInterface(new LoadListener(), "HTMLOUT");
myBrowser.loadData("", "text/html", null);
myBrowser.loadUrl(urlToBrowse);
Log.d("Stefano", "Main URL requested");
Log.d("Stefano", "JS disabled");
}
// Delayed HTML extraction
public void delayedStartHtmlExtractor(final int delay) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
myBrowser
.loadUrl("javascript:(function() {HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');})()");
Log.d("Stefano", "HTML extraction launched");
}
}, delay);
}
// Insert the HTML code in the log information
class LoadListener {
@JavascriptInterface
public void processHTML(String html) {
Log.d("Stefano", "HTML Extraction in progress...");
Log.e("HTML CODE", html);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment