Tom
Tom

Reputation: 7586

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

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.

Upvotes: 1

Views: 1398

Answers (2)

Tal Mantelmakher
Tal Mantelmakher

Reputation: 1002

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

Upvotes: 0

Tom
Tom

Reputation: 7586

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

            }

        });

Upvotes: 1

Related Questions