Addev
Addev

Reputation: 32233

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

Upvotes: 8

Views: 640

Answers (2)

katzenhut
katzenhut

Reputation: 1742

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.

Upvotes: 1

Yoni Gross
Yoni Gross

Reputation: 816

You can use http request to get the HTML page as a String, then use something like jsoup to find and replace the script, and use WebView.loadDataWithBaseURL to load the HTML content into the WebView.

Upvotes: 0

Related Questions