5

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?

dongshengcn
  • 6,434
  • 7
  • 35
  • 44
  • post your code and where you put file ? – Samir Mangroliya May 16 '12 at 14:15
  • This may be a security mechanism. I tried a file:///mnt/sdcard/some.jpg link on a test webpage, and found it would not even attempt to load when clicked on an android device. However, if I long pressed the link and selected 'open' from the popup menu, then the referenced local image actually would open. Tried it with an html file too. – Chris Stratton May 18 '12 at 17:04

1 Answers1

6

Here are a couple of things to try:

  1. 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.

  2. 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" />

  3. 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;  
        }  
    }  
AStopher
  • 4,207
  • 11
  • 50
  • 75
Theo
  • 5,963
  • 3
  • 38
  • 56