Load web-application into a webview using local paths for images stored in the application

早过忘川 提交于 2019-12-10 11:24:32

问题


I want to be able to create an app that uses WebView to request a url from an external web application which returns html and css that references images that are assets within the actual application. The idea is basically to speed up everything so that images never have to be downloaded.

Here is a simplified example:

Server HTML:

<html> 
  <head> 
  <style> 
     #myImage { background-image: url("file:///android_asset/myImage.jpg"; width: 50px; height: 50px;} 
  </style> 
  </head> 
  <body> 
    <div id="myImage"></div> 
  </body> 
</html>

So, is there any way to be able to do this? My main goal is to just have the application request all the HTML from a server, but be able to map the image urls to local resources within the application.

Thanks in advance, Leon


回答1:


Why not to load all HTML from application side? If you bother that this web page will have no access to network - use WebView.loadDataWithBaseUrl method.

For embed images into a web page you can use data:URI scheme: http://en.wikipedia.org/wiki/Data_URI_scheme

Also you can map your application images even if you are page is loaded remotely. You can use WebView.loadUrl("javascript:....") to "send" images data via JavaScript code (also using data:URI scheme).

EDIT.

Firstly, at HTML side your example with embedded images will look something like this:

<html> 
  <head> 
  <style> 
     #myImage { background-image: url('data:image/png;base64,iVBORw0KG.....'); width: 50px; height: 50px;} 
  </style> 
  </head> 
  <body> 
    <div id="myImage"></div> 
  </body> 
</html>

When, if you want to store this page at the application side, you can store it somewhere (string resource, asset folder) and when get it.

String pageResource = // get it somehow
WebView myWebView;

myWebView.loadDataWithBaseUrl(
    "http://my.site.com",  // The base url
    pageResource,          // page content to load...
    "text/html",           // it's MIME type...
    "UTF-8",               // and encoding
    "http://my.site.com/page.html");

Now the WebView has loaded your page. It is loaded from local resources but from WebView point of view it is like it is loaded from the network. It has access to network resources and JavaScript code working here as well (this is the main difference between loadData and loadDataWithBaseUrl).



来源:https://stackoverflow.com/questions/5350987/load-web-application-into-a-webview-using-local-paths-for-images-stored-in-the-a

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