3

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
Czechnology
  • 14,832
  • 10
  • 62
  • 88
  • check http://stackoverflow.com/questions/3039555/android-webview-anchor-link-jump-link-not-working – Fortega Feb 27 '13 at 15:31
  • @Michaël you might want to check out this [meta question](http://meta.stackexchange.com/q/158228/148672) – Conrad Frix Feb 27 '13 at 15:42
  • @Fortega, thanks for the link! The strange thing is that while many other report that WebView is simply ignoring the fragment, in my case it fails to load the page if I add fragment to a working url! – Czechnology Feb 27 '13 at 15:55

1 Answers1

2

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;
    }
});
Community
  • 1
  • 1
Dima Kornilov
  • 2,003
  • 3
  • 16
  • 25