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

后端 未结 7 1838
北恋
北恋 2020-11-22 06:19

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

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

It seems WebView

7条回答
  •  盖世英雄少女心
    2020-11-22 07:11

    Per issue 12987, Blundell's answer crashes (at least on my 2.3 VM). Instead, I intercept a call to console.log with a special prefix:

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

提交回复
热议问题