Load web-application into a webview using local paths for images stored in the application
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:///and开发者_开发知识库roid_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
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
).
精彩评论