final WebView webview = (WebView) findViewById(R.id.webView1);
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webview.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, final String url) {
String oAuthUrl="http://www.google.com";
if(url.contains(oAuthUrl))
webview.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
}
});
webview.loadUrl("http://www.google.com");
MyJavaScriptInterface类
class MyJavaScriptInterface
{
@SuppressWarnings("unused")
public void processHTML(final String html)
{
Log.i("processed html",html);
Thread OauthFetcher=new Thread(new Runnable() {
@Override
public void run() {
String oAuthDetails=null;
oAuthDetails=Html.fromHtml(html).toString();
Log.i("oAuthDetails",oAuthDetails);
}
});OauthFetcher.start();
}
}
我发现堆栈中的代码溢出。我运行了这个应用程序,但我没有在我的webview页面中获取源代码。我想获得webview的源代码,等于String。我能怎么做?
答案 0 :(得分:1)
确保您已将@JavascriptInterface
添加到processHTML方法。如果您已将targetSdkVersion设置为17或更高,则必须将@JavascriptInterface注释添加到您希望JavaScript可用的任何方法(该方法也必须公开),看看here。
class MyJavaScriptInterface
{
@JavascriptInterface
public void processHTML(final String html)
{
Log.i("processed html",html);
Thread OauthFetcher=new Thread(new Runnable() {
@Override
public void run() {
String oAuthDetails=null;
oAuthDetails=Html.fromHtml(html).toString();
Log.i("oAuthDetails",oAuthDetails);
}
});OauthFetcher.start();
}
}