Is there a way to determine when WebView has loaded the HTML? (so when the DOM is ready)

1.1k Views Asked by At

I'd like the inject javascript into the WebView as soon as the HTML is loaded and the DOM is ready, so not waiting for the all assets.

I know about onPageFinished, but it is called when everything is loaded. I'd like a callback sooner when the DOM is ready.

2

There are 2 best solutions below

2
Tal Mantelmakher On

You can set a JS lisntener interface on the WebView, and call it in onload in your HTML

Here's an example

EDIT

Since you mentioned you cannot modify the HTML, try this:

webView.setWebChromeClient(new MyWebChromeClient(context));

private final class MyWebChromeClient extends WebChromeClient{
    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        if (newProgress == 100){
           // loading done
        }
        super.onProgressChanged(view, newProgress);
    }
}
0
Tom On

Solved it by injecting a javascript event listener in onPageStarted:

web.setWebViewClient( new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                view.loadUrl("javascript:document.addEventListener('DOMContentLoaded', (event) => { <your stuff> })");

            }

        });