在 WebView 中访问本地文件 [英] Access local file in a WebView
问题描述
我的本机应用程序包括一个 WebView,并且 WebView 加载了一个离网的网页.例如,html是从
加载的http://dongshengcn.com/test.html
似乎从网络(而不是本地)加载的任何页面都无法从本地设备加载任何文件.
我的问题是:
是否可以将 http://dongsheng.com/test.html 加载到 webview(作为本机应用程序的一部分)访问本地设备上的文件?
这里有几件事情可以尝试:
要使用本地文件,您需要将它们放在项目的资产文件夹中,并使用诸如 file:///android_asset/之类的 URL 调用它们.例如,如果您在 assets 文件夹中添加 mypage.html,那么您可以在 webview 中使用 file:///android_asset/mypage.html 调用它.
检查以确保您在 Manifest 中拥有适当的 webview 权限.要使 webview 正常工作,您需要:
看看 Github 上的以下应用程序,作为奖励,它还修复了 Honeycomb 和 ICS 中的 webview 的几个错误.这是关于如何将 webview 与本地文件一起使用的完整示例:https://github.com/bricolsoftconsulting/WebViewIssue17535FixDemo
问题澄清后的附录:
是的,可以从网络加载本地页面,但您必须使用技巧来绕过浏览器的安全措施.
用自定义方案替换 URL 的 file://android_asset/部分(例如 file//android_asset/mypage.html 变为 myscheme:///mypage.html),并将这些自定义方案 URL 放在您的页面中.实现 WebViewClient 的 shouldOverrideUrlLoading
,检查 URL 是否以自定义方案开头,如果是,则使用 webview.loadUrl 重定向到本地页面.
My native app includes a WebView, and the WebView loads a web page off web. For example, the html is loaded from
http://dongshengcn.com/test.html
It seems any page loaded from web (instead of local) can not load any file from local device.
My question is:
Is it possible for a http://dongsheng.com/test.html loaded to a webview (as part of native app) to access file on local device?
Here are a couple of things to try:
To use local files you need to place them in your project's assets folder and invoke them using URLs such as file:///android_asset/. For example, if you add mypage.html in your assets folder, then you can invoke it in the webview with file:///android_asset/mypage.html.
Check to make sure that you have the appropriate webview permissions in your Manifest. For the webview to work correctly, you need:
<uses-permission android:name="android.permission.INTERNET" />
Take a look at the following app on Github, which as a bonus also fixes a couple of bugs with the webview in Honeycomb and ICS. It is a full example on how to use the webview with local files: https://github.com/bricolsoftconsulting/WebViewIssue17535FixDemo
EDIT: Addendum after question clarification:
Yes, it is possible to load a local page from the web, but you must use a trick to bypass the browser's security measures.
Replace the file://android_asset/ portion of the URLs with a custom scheme (e.g. file///android_asset/mypage.html becomes myscheme:///mypage.html), and place these custom scheme URLs in your page. Implement WebViewClient's shouldOverrideUrlLoading
, check if the URL begins with the custom scheme and if so redirect to the local page using webview.loadUrl.
mWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url != null && url.startsWith("myscheme://")) { String newUrl = url.replace("myscheme://", "file://android_asset/"); mWebView.loadUrl(newUrl); return true; } return false; } }
这篇关于在 WebView 中访问本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!