How to access local assets from a remote URL in Android WebView?

≡放荡痞女 提交于 2019-12-05 01:53:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!