Search code examples
javaandroidwebviewjsoup

Remove Background Image with Jsoup in Android Studio


I build apps with WebView and Jsoup for remove elements with unique Id or Class. But i have a problem to remove background image with Jsoup. This is my code with Jsoup for remove background image.

private class MyAsyncTask extends AsyncTask<Void, Void, Document> {

    @Override
    protected Document doInBackground(Void... voids) {
        String url = "https://www.mywebsite.com/";

        Document document = null;
        try {
            document = Jsoup.connect(url).get();

            document.getElementsByAttribute("url(\"https://www.mywebsite.com/assets/style/lapor/images/body-background.jpg\")").remove();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return document;
    } }

url that i want to remove

Thank you.


Solution

  • Look at JavaDoc of getElementsByAttribute method. It expects a name of the attribute as a parameter but you've provided the value of a css property instead. It's obiously wrong and it's not gonna work.

    In addition Jsoup is a library for working with HTML. That means you could read, traverse and manipulate a DOM tree of a document but not it's style. I don't think query elements by their style is supported.

    However you may fulfill your requirements by:

    • Query elements with background image (however you need to know in advance which elements you need to modify).
    • Add style attribute to them, overriding a background-image rule.

    For the case you've provided it should work when you replace the line:

    document.getElementsByAttribute("url(\"https://www.mywebsite.com/assets/style/lapor/images/body-background.jpg\")").remove();
    

    ... to the following:

    document.body().attr("style", "background-image: none;")