Android Development: Using Image From Assets In A WebView's HTML

Viewed 34690

In my app I'm making a basic HTML help document. I wanted my app's logo in the HTML img tag itself, but I don't know how I'd reference to the logo which will be stored in assets.

Is this possible, if so how?

Thanks for the help!

6 Answers

Consider we have placed an image your_image.png in assets/imgs.

In earlier versions of android you can directly access images like below.

webView.loadData("<img src='file:///android_asset/imgs/your_image.png'/>",
        "text/html", "UTF-8");

But can't access files directly in latest versions due to added security concerns. for the latest versions we need to use WebViewAssetLoader. refer the below code.

Helper class to load local files including application's static assets and resources using http(s):// URLs inside a WebView class. Loading local files using web-like URLs instead of "file://" is desirable as it is compatible with the Same-Origin policy.

    final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
            .addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this))
            .build();

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view,
                                                          WebResourceRequest request) {
            return assetLoader.shouldInterceptRequest(request.getUrl());
        }
    });
    webView.loadData("<img src='https://appassets.androidplatform.net/assets/imgs/your_image.png'/>",
            "text/html", "UTF-8");

for more information please refer android dev portal links https://developer.android.com/reference/androidx/webkit/WebViewAssetLoader https://developer.android.com/jetpack/androidx/releases/webkit?fireglass_rsn=true

Related