0
class MyJavaScriptInterface
{
  @SuppressWarnings("unused")
  public void processHTML(String html)
  {
    // process html
  }
}

final WebView browser = (WebView)findViewById(R.id.browser);
browser.getSettings().setJavaScriptEnabled(true);

browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

browser.setWebViewClient(new WebViewClient() {
  @Override
  public void onPageFinished(WebView view, String url)
  {
    new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
      browser.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
    }
  }, 2000);
}
});

browser.loadUrl("someurl");

What I want to achieve is to call the processHTML method only when all the javascripts are loaded on the page (usually 2-3 seconds after onPageFinished occurred).

The rude solution I found is to use a delayed handler but i would ask if there is a way to know when all the scripts are loaded.

I could loop that handler until I don't find the info I want but it doesn't seem to be an elegant solution.

1911z
  • 1,073
  • 10
  • 15

1 Answers1

0

What about this:

    webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            new Thread(){
                public void run(){
                    try {sleep(2000); } catch(Throwable t){} //change 2 000 ms if you want
                    runOnUiThread(new Runnable(){
                        public void run() {
                            webview.loadUrl("javascript:window.HtmlViewer.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
                        }
                    }
            }}.start();
        }
    });

class MyJavaScriptInterface {
    MyJavaScriptInterface(Context ctx) {
    }
    @JavascriptInterface //add this, if your target api is higher than 17
    public void showHTML(String html) {
         //html is your code
    }
}

Source: how to get html content from a webview?

You cannot get info, is all script loaded. Somes script (for example online stoper) uses always JavaScript and it will not end. (sry for my bad english)

Community
  • 1
  • 1
barwnikk
  • 950
  • 8
  • 14