如何从 WebView 获取网页内容? [英] How do I get the web page contents from a WebView?

查看:57
本文介绍了如何从 WebView 获取网页内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Android 上,我有一个显示页面的 WebView.

On Android, I have a WebView that is displaying a page.

如何在不再次请求页面的情况下获取页面源?

How do I get the page source without requesting the page again?

似乎 WebView 应该有某种返回字符串的 getPageSource() 方法,但可惜它没有.

It seems WebView should have some kind of getPageSource() method that returns a string, but alas it does not.

如果我启用 JavaScript,在此调用中放入什么合适的 JavaScript 来获取内容?

If I enable JavaScript, what is the appropriate JavaScript to put in this call to get the contents?

webview.loadUrl("javascript:(function() { " +  
    "document.getElementsByTagName('body')[0].style.color = 'red'; " +  
    "})()");  

推荐答案

我知道这是一个迟到的答案,但我发现了这个问题,因为我遇到了同样的问题.我想我在关于 lexandera 的这篇文章中找到了答案.com.下面的代码基本上是从网站上剪切和粘贴的.似乎可以解决问题.

I know this is a late answer, but I found this question because I had the same problem. I think I found the answer in this post on lexandera.com. The code below is basically a cut-and-paste from the site. It seems to do the trick.

final Context myApp = this;

/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
    @JavascriptInterface
    @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('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
    }
});

/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");

这篇关于如何从 WebView 获取网页内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆