Android Webview Anchor Link (Jump link) not working

前端 未结 7 1222
后悔当初
后悔当初 2020-12-01 06:53

I have a WebView in my Android App that is loading an HTML string using the loadDataWithBaseURL() method. The problem is that local anchor links (

7条回答
  •  粉色の甜心
    2020-12-01 07:07

    WebView in Android 4.0 fails to open URLs with links in them. e.g. "file:///android_asset/help.html#helplinkcontacts"

    Here is how I got around it

    WebView wv = (WebView) nagDialog.findViewById(R.id.wv);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.setWebViewClient(new MyWebViewClient(link));
    wv.loadUrl("file:///android_asset/help.html");
    

    And define the custom WebViewClient class

    class MyWebViewClient extends WebViewClient {
        private String link;
    
        public MyWebViewClient(String link) {
            this.link = link;
        }
    
        @Override
        public void onPageFinished(WebView view, String url) {
            if (!"".equals(link) && link != null)
                view.loadUrl("javascript:location.hash = '#" + link + "';");
        }
    }
    

提交回复
热议问题