Search code examples
androidandroid-webview

Relative paths in HTML from `filesDir` won't work


I am trying to load html from filesDir using webview.loadDataWithBaseURL(baseUrl, htmlString). The relative paths in the HTML won't work hence it loads without styles, javascript and images.

The baseUrl that I am providing is file:///data/user/0/com.mydomain.app/files/folder/index.html The issue gets resolved when the baseUrl is changed to file:///android_asset/folder/index.html.

Note : Currently the assets are present in both android_asset as well as filesDir folders; but I am planning to remove the assets from android_asset folder.

In App file structure

main
  assets
    folder
      index.html
    utils
      style.css
      script.js
    images
      image.jpg
  java
  res

filesDir (Persistant Files) structure

com.mydomain.app
  cache
  files
    folder
      index.html
    utils
      style.css
      script.js
    images
      image.jpg

Content of index.html is passed as htmlString.

<head>
  <link rel="stylesheet" href="../utils/style.css"/>
</head>
<body>
  <img src="../images/image.jpg"/>
  <script src="../utils/script.css" />
</body>

Solution

  • I believe you need to call setAllowFileAccess in WebSettings to enable access to file:// URLs, as they're disabled by default in API 30 and above.

    webview.getSettings().setAllowFileAccess(true);