首页 > 解决方案 > 使用 loadDataWithBaseURL 禁用 webview 中的链接

问题描述

我使用以下代码加载电子书的 html 内容,其中 templateString 包含连接到主文件中的样式表和图像的 html 内容。

String itemURL = "file://" + itemPath;
testWV.loadDataWithBaseURL(itemURL,  templateString, "text/html", "UTF-8", "about:blank");

我面临的问题是锚链接根本没有响应。

我注意到如果 itemURL 为空,或者如果我使用 loadData 而不是 loadDataWithBaseURL,链接可以工作,但我失去了图像的连接和通过 itemURL 连接的样式。

请注意,webview 可见性始终设置为可见。添加我已将以下功能添加到 webview

this.getSettings().setJavaScriptEnabled(true);
this.requestFocusFromTouch();
this.setVerticalScrollBarEnabled(false);
this.setHorizontalScrollBarEnabled(false);
this.getSettings().setSupportZoom(true);
this.getSettings().setBuiltInZoomControls(true);
this.getSettings().setDisplayZoomControls(false);
this.getSettings().setAllowContentAccess(true);
this.getSettings().setAllowFileAccess(true);
this.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
this.getSettings().setAllowFileAccessFromFileURLs(true);
this.getSettings().setAllowUniversalAccessFromFileURLs(true);

这是为 webview 初始化的 onTouch 方法:

this.setOnTouchListener(new View.OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {

        WebView.HitTestResult hr = ((WebView)v).getHitTestResult();
        System.out.println("getExtra: "+hr.getExtra());
        // getExtra always gives null when webview loaded with loadDataWithBaseURL while it should give the url of the link pressed when the user touches a link

        return false;
    }
});

如果需要更多代码,我可以分享。

标签: androidwebviewhyperlinkloaddata

解决方案


设置WebViewClient为您的webView并加载数据loadDataWithBaseURL 并传递您的基本网址

这将有助于将锚 url 加载到webview

 webview.getSettings().setJavaScriptEnabled(true);
 webview.requestFocusFromTouch();
 webview.setWebViewClient(new MyWebClient());

这是WebViewClient上课

class MyWebClient extends WebViewClient {

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    public void onPageFinished(WebView view, final String url) {
    }
}

推荐阅读