Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using loadDataWithBaseURL disables links in webview

I use the following code to load html content of ebooks where templateString contains the html content which connects to stylesheet and images in the main file.

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

The problem I'm facing is that anchor links are not responsive at all.

I noticed if itemURL was null or if I use loadData instead of loadDataWithBaseURL, the links work but I loose the connection of the images and the styling connected through the itemURL.

Kindly note that the webview visibility is always set to visible. Add I have added the following features to the 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);

This is the onTouch method initialized for the webview:

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

If further code is needed, I can share it.

like image 345
coder Avatar asked Nov 06 '22 15:11

coder


1 Answers

set WebViewClient to your webView and load data in loadDataWithBaseURL and pass your base url

this will helps to load anchor url into webview

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

here is WebViewClient class

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) {
    }
}
like image 57
Priyanka Avatar answered Nov 15 '22 23:11

Priyanka