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

后端 未结 7 2127
北恋
北恋 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:10

    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(''+document.getElementsByTagName('html')[0].innerHTML+'');");
        }
    });
    
    /* load a web page */
    browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");
    

提交回复
热议问题