Pergunta

No Android, eu tenho um WebView Isso está exibindo uma página.

Como faço para obter a fonte da página sem solicitar a página novamente?

Parece WebView deveria ter algum tipo de getPageSource() Método que retorna uma string, mas, infelizmente, não.

Se eu habilitar o JavaScript, qual é o JavaScript apropriado para colocar nesta chamada para obter o conteúdo?

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

Solução

Sei que essa é uma resposta tardia, mas encontrei essa pergunta porque tive o mesmo problema. Eu acho que encontrei a resposta em esta postagem em lexandera.com. O código abaixo é basicamente um corte e colas do site. Parece fazer o truque.

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");

Outras dicas

Por Edição 12987, A resposta de Blundell falha (pelo menos na minha vm 2,3 vm). Em vez disso, intercepto uma chamada para console.log com um prefixo especial:

// intercept calls to console.log
web.setWebChromeClient(new WebChromeClient() {
    public boolean onConsoleMessage(ConsoleMessage cmsg)
    {
        // check secret prefix
        if (cmsg.message().startsWith("MAGIC"))
        {
            String msg = cmsg.message().substring(5); // strip off prefix

            /* process HTML */

            return true;
        }

        return false;
    }
});

// inject the JavaScript on page load
web.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView view, String address)
    {
        // have the page spill its guts, with a secret prefix
        view.loadUrl("javascript:console.log('MAGIC'+document.getElementsByTagName('html')[0].innerHTML);");
    }
});

web.loadUrl("http://www.google.com");

Esta é uma resposta baseada em Jluckyiv's, mas acho que é melhor e mais simples alterar o JavaScript da seguinte maneira.

browser.loadUrl("javascript:HTMLOUT.processHTML(document.documentElement.outerHTML);");

Você já pensou em buscar o HTML separadamente e depois carregá -lo em um WebView?

String fetchContent(WebView view, String url) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    HttpEntity entity = response.getEntity();
    String html = EntityUtils.toString(entity); // assume html for simplicity
    view.loadDataWithBaseURL(url, html, "text/html", "utf-8", url); // todo: get mime, charset from entity
    if (statusCode != 200) {
        // handle fail
    }
    return html;
}

Consegui fazer isso funcionar usando o código da resposta do @jluckyiv, mas tive que adicionar @javascriptInterface Anotation ao método ProcessHTML no myjavascriptInterface.

class MyJavaScriptInterface
{
    @SuppressWarnings("unused")
    @JavascriptInterface
    public void processHTML(String html)
    {
        // process the html as needed by the app
    }
}

Você também precisa anotar o método com @javascriptInterface se o seu TargetSdkversion for> = 17 - porque existem novos requisitos de segurança no SDK 17, ou seja, todos os métodos JavaScript devem ser anotados com @javascriptInterface. Caso contrário, você verá o erro como: Uncathed TypeError: Object [Objeto do objeto] não tem método 'Processhtml' em NULL: 1

Se você estiver trabalhando no kitkat e acima, poderá usar as ferramentas de depuração do Chrome Remote para encontrar todas as solicitações e respostas entrando e saindo do seu WebView e também o código -fonte HTML da página visualizado.

https://developer.chrome.com/devtools/docs/remote-debugging

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top