WebView jump to anchor using loadDataWithBaseUrl

只谈情不闲聊 提交于 2019-11-30 20:10:20

How about control it by JavaScript? I didn't try it but maybe this is a clue.

builder.append(getThreadBody());
builder.append("<script>window.location.hash="949823";</script>");
builder.append("</body></html>");

Remember enable javascript for WebView.

----Additional Answer----

I saw that you use TimerTask to load the javascript, That works but I think there is another better way. WebView have a callback named onPageFinished and it will be trigger when WebView finish loading webpage. You could inject your JS there.

webContents.setWebViewClient(new WebViewClient(){

    @Override
    public void onPageFinished(WebView view, String url) {
          String id = "895884";
          webContents.loadUrl("javascript:scrollAnchor(" + id + ");");
    }

});

Hope this is useful!

epint

First of all, you don't need to use javascript. If you loaded content with

webContents.loadDataWithBaseURL("some://dummy/url",...);

you can simply scroll to anchor with

webContents.loadUrl("some://dummy/url#anchor");

Secondly, doing that on onPageFinished without additional control results in never ending loop! When loadUrl finishes onPageFinished get's called again and again.

If you have external action (eg: onclick event), try this code

 public static void scrollToAnchor(String id) {
        sWebView.loadUrl("javascript:document.getElementById(\"" + id + "\").scrollIntoView()");
 }

if you load the html from the assets:

 webView.loadUrl("file:///android_asset/htmls/mypage.html#anchor");

and you can move to the anchor inside a web page:

webView.loadUrl("http://www.stackoverflow.com/mypage.html#anchor");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!