Search code examples
javascriptandroidwebviewwebviewclient

Android - Add image to webview


I want to add an image from url to webview. I use evaluatejavascript function. minSdkVersion is 19. My code is below :

    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("https://www.google.com");
    String script = "function addImage() {\n" +
            "            var img = document.createElement(\"img\");\n" +
            "            img.src = \"http://weknownyourdreamz.com/images/cat/cat-01.jpg\";\n" +
            "            document.body.insertBefore(img, document.body.firstChild);\n" +
            "        }\n" +
            "        if (document.readyState === \"complete\")\n" +
            "            addImage();\n" +
            "        else\n" +
            "            document.onload = addImage();";

    webView.evaluateJavascript(script, null);

It adds an item but not real image. This javascript codes works on ios.


Solution

  • Add the line below to make the images load automatically.

    webView.getSettings().setLoadsImagesAutomatically(true);
    

    Also if you are on lollipop or above and you want to allow mixed content, you can use :

    webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);