How to scroll to a named anchor in WebView url?

2.6k Views Asked by At

I'm having a compatibility problems opening a locally stored page on a specific named anchor in Android'd WebView. Currently I'm using simply

webView.loadUrl("file:///android_asset/page.html#fragment");

which works fine on my 4.1 device but users of other devices keep complaining about it not working.

For example on 4.0.3 Opening the page without the url fragment #fragment part opens fine but with it user gets a "Webpage not available" error.

I've also tried opening the fragment with a two calls to the loadUrl(String) method, first without then with fragment. Also using JavaScript to change page's location.

What more could I try?

1

There are 1 best solutions below

0
On

First of all, RFC 1738 doesn't specify URL fragment portion for file:// scheme. File URI consists of file://, hostname and path -- and that's it.

Thus, anchors in file URIs should not be supported. But for some reason, Android does support them since Jelly Bean. If you want them to work on Ice Cream Sandwich too:

private static String BASE_URL = "file:///android_asset/";

mWebView.setWebViewClient(new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        try {
            if (url.startsWith(BASE_URL) && url.contains("#")) {
                url = url.replace(BASE_URL, "");
                InputStream is = getAssets().open(url.substring(0, url.indexOf("#")));
                return new WebResourceResponse("text/html", "utf-8", is);
            }
        } catch(IOException e) {
            Log.e("DKDK", "shouldInterceptRequest", e);
        }
        return null;
    }
});