【问题标题】:Android Webview stop loading at 90% progress after JS injectionJS 注入后,Android Webview 以 90% 的进度停止加载
【发布时间】:2016-01-05 13:40:44
【问题描述】:

我有一个带有包含一些 HTML 内容和 JS 的 WebViews 的 ViewPager。

当我调用以下命令时:

public void goToAnchor(String hash) {
    this.loadUrl("javascript:alert(myapp.getAnchorOffset(\'"+hash+"\'));");
}

它正确地运行 javascript,在我的 WebChromeClient 中,我会听到在“getAnchorOffset”JS 函数中创建的警报,如下所示:

public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

            //Set the page
            int offset = Math.round(Float.parseFloat(message));

            Log.d("Anchor - ", "Offset = " + offset);
            Log.d("Anchor - ", "width = " + mWebView.getWidth());

            //Get the page
            int page = Math.round(offset / mWebView.getWidth());

            //Make the callback
            anchorListener.didGetAnchorPage(page);
            return true;
        }

这也被正确调用,并且我在变量“page”中得到了正确的值。现在有趣/烦人的部分是,当我使用 anchorListener.didGetAnchorPage 进行回调时,它会回调,但我正在使用的以下所有 webViews 都不会加载,并且进度停止在 90%。

如果我在 ViewPager 中转到第 20 页,WebView 将在 90% 处停止加载,这总是发生在我进行 JS 调用之后。

被调用的 JS 函数是这样的:

myapp.getAnchorOffset = function(elementId) {
var searchResult = $(document).find("#"+elementId).first();
if (searchResult.length == 0) {
    console.log("ERROR - no DOM element found by id: " + elementId);
    return 0;
}
return searchResult.offset().left;

};

有人知道为什么吗?

提前致谢。

【问题讨论】:

  • 我刚刚注意到,如果我将 onJsAlert 的返回值更改为 true,那么它实际上会呈现其他页面,但它也会显示警报,这是不应该发生的。如何解决这个问题?

标签: java android mobile webview


【解决方案1】:

我刚刚找到了解决方案。

诀窍是像下面这样处理 js 警报:

mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

            //Set the page
            int offset = Math.round(Float.parseFloat(message));

            Log.d("Anchor - ", "Offset = " + offset);
            Log.d("Anchor - ", "width = " + mWebView.getWidth());

            //Get the page
            int page = Math.round(offset / mWebView.getWidth());

            //Make the callback
            anchorListener.didGetAnchorPage(page + pageInEpub);
            result.cancel();
            return true;
        }

使用“result.cancel();”在返回语句之前。

【讨论】:

    猜你喜欢
    • 2018-01-01
    • 2011-09-24
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    相关资源
    最近更新 更多