我如何知道我的 WebView 已加载 100%?

发布于 2024-11-13 08:41:58 字数 1275 浏览 1 评论 0原文

我正在尝试在 WebView 中加载一些包含 JavaScript 的 HTML 代码。

现在,我想测试我的 WebView 是否在 5 秒之前加载。我尝试过 getProgress() 方法,但有时我得到进度为 100,但我的 Webview 未加载。
有没有其他方法可以确保我的 Webview 加载 100%?

这是我的代码的一部分:

sdk.getWebView().loadDataWithBaseURL("notreal/", data_html,MIME_TYPE,ENCODING_UTF_8,null);

Timer timer = new Timer();
TimerTask task = new TimerTask() {

    @Override
    public void run(){                      
    Log.i("TAG", "progress fin = "+sdk.getWebView().getProgress());

    if(sdk.getWebView().getProgress() <100){
        //cancel the webView
        sdk.getContext().runOnUiThread(new Runnable() {
             @Override
             public void run() {
            sdk.getImgView().setVisibility(View.VISIBLE);
            sdk.getWebView().setVisibility(View.GONE);
             }
        });
    }

    // else ,the Webview is loaded
    else{
        //prepare webview 
        sdk.getContext().runOnUiThread(new Runnable() {
            @Override
            public void run(){
                     // hide imageView
                     sdk.getImgView().setVisibility(View.GONE);
                     sdk.getWebView().setVisibility(View.VISIBLE);
            }
        });
    }

 }
 };
 timer.schedule(task, 5000);

I'm trying to load in my WebView some HTML code that contains JavaScript.

Now , I want to test if my WebView is loaded before 5 secondes. I've tried the method getProgress(), but sometimes I get that the progress is 100, but my Webview is not loaded.
Is there another way to be sure that my Webview is loaded 100%?

This is a part of my code :

sdk.getWebView().loadDataWithBaseURL("notreal/", data_html,MIME_TYPE,ENCODING_UTF_8,null);

Timer timer = new Timer();
TimerTask task = new TimerTask() {

    @Override
    public void run(){                      
    Log.i("TAG", "progress fin = "+sdk.getWebView().getProgress());

    if(sdk.getWebView().getProgress() <100){
        //cancel the webView
        sdk.getContext().runOnUiThread(new Runnable() {
             @Override
             public void run() {
            sdk.getImgView().setVisibility(View.VISIBLE);
            sdk.getWebView().setVisibility(View.GONE);
             }
        });
    }

    // else ,the Webview is loaded
    else{
        //prepare webview 
        sdk.getContext().runOnUiThread(new Runnable() {
            @Override
            public void run(){
                     // hide imageView
                     sdk.getImgView().setVisibility(View.GONE);
                     sdk.getWebView().setVisibility(View.VISIBLE);
            }
        });
    }

 }
 };
 timer.schedule(task, 5000);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

天冷不及心凉 2024-11-20 08:41:58

正如这里所说: 如何监听WebView加载完URL?~

boolean loadingFinished = true;
boolean redirect = false;

mWebView.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
        if (!loadingFinished) {
           redirect = true;
        }

        loadingFinished = false;
        view.loadUrl(urlNewString);
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap facIcon) {
        loadingFinished = false;
        //SHOW LOADING IF IT ISNT ALREADY VISIBLE  
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (!redirect) {
            loadingFinished = true;
        }

        if (loadingFinished && !redirect) {
            //HIDE LOADING IT HAS FINISHED
        } else {
            redirect = false; 
        }

    }
});

As said here: How to listen for a WebView finishing loading a URL?~

boolean loadingFinished = true;
boolean redirect = false;

mWebView.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
        if (!loadingFinished) {
           redirect = true;
        }

        loadingFinished = false;
        view.loadUrl(urlNewString);
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap facIcon) {
        loadingFinished = false;
        //SHOW LOADING IF IT ISNT ALREADY VISIBLE  
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (!redirect) {
            loadingFinished = true;
        }

        if (loadingFinished && !redirect) {
            //HIDE LOADING IT HAS FINISHED
        } else {
            redirect = false; 
        }

    }
});
山人契 2024-11-20 08:41:58

检测页面是否已呈现的最佳方法是使用 onPageCommitVisible 回调,可从 API 23 获得。 onPageLoadFinished 不合适,因为它传递得太快(当处理 HTML 时,但是尚未渲染)。

webview.setWebViewClient(new WebViewClient() {

    @Override
     public void onPageCommitVisible (WebView view, 
            String url)
    }
}

The best way to detect if a page has rendered is to use the onPageCommitVisible callback, available from API 23. onPageLoadFinished is not suitable, since it's delivered too soon (when the HTML is processed, but not yet rendered).

webview.setWebViewClient(new WebViewClient() {

    @Override
     public void onPageCommitVisible (WebView view, 
            String url)
    }
}
豆芽 2024-11-20 08:41:58
webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress == 100) {
                    //do your task

                }
            }
        });
webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress == 100) {
                    //do your task

                }
            }
        });
暮年慕年 2024-11-20 08:41:58

您需要覆盖 WebViewClientonPageFinished

这是一个给您的示例

private class Callback extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }


    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        //do what you want to do

        }


}

You need to overwrite the onPageFinished of WebViewClient

Here is an example for you

private class Callback extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }


    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        //do what you want to do

        }


}
书信已泛黄 2024-11-20 08:41:58

您可以尝试扩展 WebChromeClient,覆盖 onProgressChanged(WebView view, int newProgress) 并使用 setWebChromeClient(WebChromeClient) 方法将其注册到您的 WebView 上。这将使您的应用程序从您启动的附加线程中解放出来,该线程只是为了检查进度是否发生变化。使用回调,更简单。所以这是第一件事。

另一个是,我也在尝试这种进度状态,并且得出了一些关于它的行为方式的结论:

  • 对于某些用例(例如检查页面是否在给定的 url 下),它必须大于 10。当 WebView连接到提供的 url 然后它会自动将进度值设置为 10,即使没有成功连接,如果它大于 10,那么您可以确定 url 可以访问并且加载已经开始,
  • 进度将返回为当您在 WebView 上调用 stopLoading() 时,为 100%,
  • 当 WebView 无法加载完整站点时(例如,图像将超时),请记住前面的一点它会报告页面已完全加载(100%)

总而言之,此进度条是 WebView 是否已完成加载网站的指示器,但就 WebKit 而言,而不是页面已完全下载。您必须记住,连接可能会崩溃,资源(图像、CSS、JS)可能由于某种原因无法加载,JavaScript 可以在页面完成加载时加载更多资源等。此进度无法告诉您网站是否内容是否完全加载,它告诉你WebView认为这应该是全部。

关于如何检查页面是否完全加载,我没有其他想法,我认为这是唯一的方法。

You can try to extend WebChromeClient, override onProgressChanged(WebView view, int newProgress) and register it on your WebView with setWebChromeClient(WebChromeClient) method. This will free your application from the additional thread that you are starting just to check whether progress changed. Use the callback, it is simpler. So that would be the first thing.

Another one is that I was also experimenting with this progress status and I came to some conclusions about how it behaves:

  • for some use cases (such as check if page is even under the given url) it has to be greater then 10. When WebView makes the connection to the url provided then it automatically sets the progress value to 10 even if it did not make a successful connection, if it is greater then 10, then you can be sure that url could be accessed and the loading has begun,
  • progress will be returned as 100% when you call stopLoading() on your WebView,
  • keeping previous point in mind also when WebView won't be able to load the full site (it will get a timeout for an image for example) then it will report that page was fully loaded (100%)

To sum up, this progress bar is an indicator on whether WebView has finished loading the site or not but in terms of WebKit not in terms of page being completely downloaded. You have to keep in mind that connection may crash, resources (images, css, js) may not load for some reason, JavaScript can load some more resources when page will finish up loading etc. this progress can't tell you if the sites content was fully loaded or not, it tells you that WebView thinks that this should be all.

I have no other ideas on how to check whether page was fully loaded or not, I think this is the only way.

薄情伤 2024-11-20 08:41:58

上述解决方案对我来说不起作用,我想确保页面加载 100%,然后注入 javascript 对页面进行一些深入研究。我想出了以下解决方案,与 NeTeInStEiN 提供的解决方案几乎没有什么偏差。这可能并不适合每个人,但它对我有用。同样,这取决于您想要从完成的页面中实现什么目标。

String url; is from your activity which want to load this url
    private class ExtendedWebViewClient extends WebViewClient {
        private int webViewPreviousState;
        private final int PAGE_STARTED = 0x1;
        private final int PAGE_REDIRECTED = 0x2;
        public void onPageStarted(WebView paramWebView, String paramString,
                Bitmap paramBitmap) {
            super.onPageStarted(paramWebView, paramString, paramBitmap);
            if(paramString.contentEquals(url)) {
                webViewPreviousState = PAGE_STARTED;
            } else {
                webViewPreviousState = PAGE_REDIRECTED;
            }
// DO YOU STUFF IF NEEDED
}
        public void onPageFinished(WebView paramWebView, String paramString) {
            if (webViewPreviousState == PAGE_STARTED) {
// I AM GETTING HERE WHEN MY PAGE IS LOADED 100%
// NOW ITS TIME FOR ME TO RUN JAVASCRIPT FUNCTIONS
// DO YOUR STUFF
}
}

希望这有帮助。

Above solutions did not work for me, I wanted to make sure I have page loaded 100% and then inject javascript to do some intensive research on the page. I came up with following solution with little deviation from the solution provided by NeTeInStEiN. This may not work for everyone but it worked for me. Again it depends on what you are trying to achieve from the finished page.

String url; is from your activity which want to load this url
    private class ExtendedWebViewClient extends WebViewClient {
        private int webViewPreviousState;
        private final int PAGE_STARTED = 0x1;
        private final int PAGE_REDIRECTED = 0x2;
        public void onPageStarted(WebView paramWebView, String paramString,
                Bitmap paramBitmap) {
            super.onPageStarted(paramWebView, paramString, paramBitmap);
            if(paramString.contentEquals(url)) {
                webViewPreviousState = PAGE_STARTED;
            } else {
                webViewPreviousState = PAGE_REDIRECTED;
            }
// DO YOU STUFF IF NEEDED
}
        public void onPageFinished(WebView paramWebView, String paramString) {
            if (webViewPreviousState == PAGE_STARTED) {
// I AM GETTING HERE WHEN MY PAGE IS LOADED 100%
// NOW ITS TIME FOR ME TO RUN JAVASCRIPT FUNCTIONS
// DO YOUR STUFF
}
}

Hope This helps.

那伤。 2024-11-20 08:41:58

我也有一个解决方案,因为已经经历了加载完成后需要显示 webview 的情况。希望大家能够理解。

    webview.loadUrl(url)
    webview.webViewClient = object : WebViewClient() {

        override fun onPageCommitVisible(view: WebView?, url: String?) {
            webview.visibility = View.GONE
            // your method to call the css and load it into the existing webview
            loadCSS()
            super.onPageCommitVisible(view, url)
        }
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            if (webview.progress == 100) {
                webview.visibility = View.VISIBLE
            }
            progressBar.visibility = View.GONE
        }
    }

I also have a solution for that because already went through the condition where need to show webview after loading finish. Hope you guys understand it.

    webview.loadUrl(url)
    webview.webViewClient = object : WebViewClient() {

        override fun onPageCommitVisible(view: WebView?, url: String?) {
            webview.visibility = View.GONE
            // your method to call the css and load it into the existing webview
            loadCSS()
            super.onPageCommitVisible(view, url)
        }
        override fun onPageFinished(view: WebView?, url: String?) {
            super.onPageFinished(view, url)
            if (webview.progress == 100) {
                webview.visibility = View.VISIBLE
            }
            progressBar.visibility = View.GONE
        }
    }
辞旧 2024-11-20 08:41:58

下面的代码完美运行。一旦页面加载成功,就会触发 onPageFinished()

        webView.setWebViewClient(new WebViewClient(){

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Toast.makeText(getApplicationContext(),"Started",Toast.LENGTH_SHORT).show();
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Toast.makeText(getApplicationContext(),"Loaded",Toast.LENGTH_SHORT).show();
            super.onPageFinished(view, url);
        }
    });

The below code works perfectly. Once the page has been loaded successfully it will trigger onPageFinished()

        webView.setWebViewClient(new WebViewClient(){

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Toast.makeText(getApplicationContext(),"Started",Toast.LENGTH_SHORT).show();
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Toast.makeText(getApplicationContext(),"Loaded",Toast.LENGTH_SHORT).show();
            super.onPageFinished(view, url);
        }
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文