Disabling links in android WebView

北城以北 提交于 2019-12-21 05:33:10

问题


First, I am quite green in the world of programming, so forgive me if my question lacks clearance in any part. I am currently trying to make an app which requires links cannot be executed in the WebView - or in another browser for that sake. I have managed to put the following two links, In Android Webview, am I able to modify a webpage's DOM? and Titanium Appcelerator Quickie: Disable links in Webview, together and create the following working code:

private class WebClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) 
    {       
        view.loadUrl("javascript:document.body.innerHTML = document.body.innerHTML.replace(/<a.*href=/gi,'<a href=\"#\" _url=');");       
    }
}

The snippet above is placed before the onCreate-method and is referenced in the onCreate-method like this:

    viewer = (WebView) findViewById(R.id.wv_engine);
    viewer.setWebViewClient(new WebViewClient());
    viewer.loadUrl(content);

Now, the code works... But only after the requested webpage has been loaded a second time. The first time I execute the WebView, example.com has all its links intact, clickable and executedable. Using the backbutton, exiting the WebView and entering it again renders all the links disabled by changing

<a href="http://www.example.com">link</a>

to

<a href="#" _url="http://www.example.com">link</a>

Now, I a theory which I am not at all sure about (I am no programmer). I believe the JavaScript is executed to slow, which results in the links-manipulation never happening. That is why it works the second time working instead with with cache. I got those thought from reading this discussion. However I have no idea how to correct it.

So my question goes: How can I make sure that none of the links of the displayed website can ever be used? Is there a way to make manipulation happen before the site is displayed?

Thanks for your time and effort. This is truly an amazing community ;)

  • Krede

回答1:


I think this is wrong:

viewer.setWebViewClient(new WebViewClient());

I guess you mean this instead:

viewer.setWebViewClient(new WebClient());

This explains why urls are not disabled at 1st load. But I don't understand why they are disabled 2nd time.

Additionally, I think you should remove this:

view.loadUrl(url);


来源:https://stackoverflow.com/questions/7416142/disabling-links-in-android-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!