4

To load an asset in HTML, I am using the URL file:///android_asset/my_image.png. It works when I am loading HTML locally, for instance, using a WebView.loadData() method.

However, I am unable to load a local asset from a remote web site, for instance, when I load a page using WebView.loadUrl("http://example.com/my_page.html"). It shows the page, but the image is not loaded.

How can I fix this problem?

UPDATE:

tarkeshwar mentioned that it is not possible because of security reasons. I understand when you open a web page in a browser, then you as a user are unable to control what the web page is accessing. And it is also a bit different to access local file system when you may read sensitive data of the user. Here I would like just to access application assets.

A workaround could be, to download the page and load it into the WebView using loadData() method. But there might be some security switch to allow WebView to access local assets.

UPDATE2: I need to support Android 2.3+.

TN.
  • 18,874
  • 30
  • 99
  • 157

2 Answers2

1

Extend WebViewClient and override shouldInterceptRequest to load the file locally. The urls would all appear remote but you can selectively load which every you need.

http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest(android.webkit.WebView, java.lang.String)

Also answered here: webview shouldinterceptrequest example

Community
  • 1
  • 1
dres
  • 1,172
  • 11
  • 15
  • Yes, unfortunately this requires API 11. – TN. Aug 06 '13 at 08:24
  • The only way to do it in earlier versions is to, like you said, download the page and load it as a string locally, so that it can access local resources. That is an option I considered for what I'm doing but I chose instead to require API 11. The JavaScript in API <11 is missing key functions as well. – dres Aug 24 '13 at 13:50
1

You can't link to a local resource from an external page. That is due to security reasons.

See Pekka's answer for a similar question: How to show local picture in web page?

Community
  • 1
  • 1
tarkeshwar
  • 4,105
  • 4
  • 29
  • 35