问题
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+.
回答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?
回答2:
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
来源:https://stackoverflow.com/questions/6212428/how-to-access-local-assets-from-a-remote-url-in-android-webview