Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a replacement over the webs loaded in a Webview

I'm implementing an app using a webview. For the urls loaded in the webview I'd need to perform a replacement over the html code loaded in the url.

How can I do this in a efficient way?

Explanation: I need to replace an specific script script from the source:

In example: I want to

<html>
    <script> SCRIPT A</script>
    <p>Hello World</p>
</html>

I want to display the user this other

<html>
    <script> SCRIPT B</script>
    <p>Hello World</p>
</html>

Thanks

like image 781
Addev Avatar asked Jan 20 '17 09:01

Addev


Video Answer


1 Answers

You have to override shouldInterceptRequest of WebViewClient. See the docs here.

The general form would be something like this (untested):

webview.setWebViewClient(new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
        if (you_want_to_intercept) {
            /*return custom WebresourceResponse here*/
        } else {
            /*call superclass*/
            return super.shouldInterceptRequest(view, url);
        }
    }
}

I hope this helps, let me know if not.

like image 97
katzenhut Avatar answered Oct 05 '22 23:10

katzenhut