How can I make webview use the HTML5 cache manifest? - android

On Android devices up to and including 4.4.2, the default Browser and Chrome support the HTML5 cache manifest. However, on those same devices, the WebView component does not seem to support the HTML5 cache manifest. Does anybody know how I can make the WebView component support the HTML5 manifest?

webView.getSettings().setDomStorageEnabled(true);
// Set cache size to 8 mb by default. should be more than enough
webView.getSettings().setAppCacheMaxSize(1024*1024*8);
// This next one is crazy. It's the DEFAULT location for your app's cache
// But it didn't work for me without this line
webView.getSettings().setAppCachePath("/data/data/"+ getPackageName() +"/cache");
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

Try this code:
private void enableHTML5AppCache() {
webView.getSettings().setDomStorageEnabled(true);
// Set cache size to 8 mb by default. should be more than enough
webView.getSettings().setAppCacheMaxSize(1024*1024*8);
// This next one is crazy. It's the DEFAULT location for your app's cache
// But it didn't work for me without this line
webView.getSettings().setAppCachePath("/data/data/"+ getPackageName() +"/cache");
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
}
Here the link.

#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl)
{
// The magic redirect
if( "http://HTML5app.com/app/".equals(failingUrl) ) {
// main.html is the place we are redirected to by the server if we are online
mWebView.loadUrl("http://HTML5app.com/app/main.html");
return;
}
else if( "http://HTML5app.com/app/main.html".equals(failingUrl) ) {
// The cache failed - We don't have an offline version to show
// This code removes the ugly android's "can't open page"
// and simply shows a dialog stating we have no network
view.loadData("", "text/html", "UTF-8");
showDialog(DIALOG_NONETWORK);
}
}
Above method will be used to handle redirection in offline scenario. [For implementing appcache and path refer previous comment.
Reference Link : HTML5 Cache mechanism in android

Related

Webview Webpage not available ERR_FILE_NOT_FOUND

I have been working on an android application, using Kotlin. Recently, I have been trying to implement video calls using Javascript with the help of Webview in android, the problem is that when loading the activity in which the Webview is in, it does not show the HTML page.
As far as I know, everything is in place, and the code from what I've researched should be fine. I have already rebuilt the application and it still does not work.
That code box below shows the supposed correct way to load the page, but I only get a: "ERR_FILE_NOT_FOUND"
val filePath = "file:///android_asset/Content/call.html"
webView.loadUrl(filePath)
Then I tried to access the page using the following syntax for the filepath:
val filePath = "./src/main/assets/Content/call.html"
And it worked, it stopped showing the error, but this is a problem, because it doesn't work like that on physical devices.
There is also this error that shows in logcat:
E/AndroidProtocolHandler: Unable to open asset URL: file:///android_asset/Content/call.html
I have also tried moving the files outside of the Content folder, does not work.
This is perhaps a very simple mistake, but I can't find the solution. It would be highly appreciated if any of you could help me, thank you.
You should be using a WebViewAssetLoader. This is the android recommended way to load static webpages and you should not be using file path.
WebviewAssetLoader will host the files in the below path - http(s)://appassets.androidplatform.net/assets/...
In your case it would be - https://appassets.androidplatform.net/assets/Content/call.html
Sample code :
final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
.addPathHandler("/assets/", new AssetsPathHandler(this))
.build();
webView.setWebViewClient(new WebViewClient() {
#Override
#RequiresApi(21)
public WebResourceResponse shouldInterceptRequest(WebView view,
WebResourceRequest request) {
return assetLoader.shouldInterceptRequest(request.getUrl());
}
#Override
#SuppressWarnings("deprecation") // for API < 21
public WebResourceResponse shouldInterceptRequest(WebView view,
WebResourceRequest request) {
return assetLoader.shouldInterceptRequest(Uri.parse(request));
}
});
WebSettings webViewSettings = webView.getSettings();
// Setting this off for security. Off by default for SDK versions >= 16.
webViewSettings.setAllowFileAccessFromFileURLs(false);
// Off by default, deprecated for SDK versions >= 30.
webViewSettings.setAllowUniversalAccessFromFileURLs(false);
// Keeping these off is less critical but still a good idea, especially if your app is not
// using file:// or content:// URLs.
webViewSettings.setAllowFileAccess(false);
webViewSettings.setAllowContentAccess(false);
// Assets are hosted under http(s)://appassets.androidplatform.net/assets/... .
// If the application's assets are in the "main/assets" folder this will read the file
// from "main/assets/www/index.html" and load it as if it were hosted on:
// https://appassets.androidplatform.net/assets/www/index.html
webview.loadUrl("https://appassets.androidplatform.net/assets/www/index.html");
I just solved my specific problem.
It turns out that my "assets" folder was not inside the "main" folder, but inside a different folder in "src". I just created a new assets folder inside "main" and placed the files there, now the HTML page loads properly. Had to go into project view.

Android WebView is taking more time to load website then the browser in laptop, both laptop and android mobile are using same internet connection

Is there something I am missing to set some property of webview?
I have set following property but no improvement in performance:
webview.setWebViewClient(new myWebClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
// Enable the caching for web view
webview.getSettings().setAppCacheEnabled(true);
// Specify the app cache path
webview.getSettings().setAppCachePath(getCacheDir().getPath());
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
if (Build.VERSION.SDK_INT >= 19) {
webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else {
webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
Any help will be highly appreciated, Thanks in advance.
Actually you are using webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); which disallows any kind of caching in your Android WebView.
While browsing in browser, most of your content is loaded from cache, which results in difference of loading time. Hence, affects overall performance.
You should use it as follows to improve caching:
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

mozilla pdf.js webview ask for internet

I'm using mozilla/pdf.js to display a pdf in a webview in my Android application. The framework doesn't need any internet connection to render the pdf. If downloaded the .js file and everything so it can use that. Still every time I want to open a new pdf Android opens the default browser with the wireless settings dialog.
After closing the app and opening it again the PDF is rendered. My internet connection both wireless as data is disabled, so it doesn't need anything of internet, I'm sure about that.
How can I solve this that the webview ask for internet?
This is my code:
webView = (WebView) findViewById(R.id.webViewWindow);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setBuiltInZoomControls(true);
webView.setWebChromeClient(new WebChromeClient());
webView.loadUrl("file:///android_asset/pdfviewer/index.html");
I also found on the Android dev page that the setAllowFileAccessFromFileURL and the setAllowUniversalAccessfromFileURLS are both not necessary. You should use only the universal one, is this true or do I understand this incorrectly?
I solved this problem by:
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d("Debug","Error");
}
});
Then you have control about the error and you can like me choose to do nothing.

Android WebView window.onload event issue

I am working on one Android App where I am loading local file contents into webview using following syntax.
url = "file://" + mLocalFilePath + java.io.File.separator + CURRENT_FILE;
webView.loadUrl(url);
The issue is the webview loads file contents and also loads the various images from url present in webpage ( webpage has many images ).
The challenge I am facing is I want to get notified when webview finish rendering entire html page.I want to get notified when webpage is 100% loaded.
I reffered various forums and also tried using
window.onload function
as well as
public void onPageFinished(WebView view, String url)
But I did not get desire output,I get callback before html page is completely loaded.I am looking for way so that I will get notified only when webpage has finished rendering all the images present in web page.( i.e Webpage is 100% loaded.)
I am not looking for complete answer even hints will be appreciated.
Thanks
Try this way
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if(newProgress==100){
// page loading completes
}
}
});
I used deprecated PictureListener that start when all images on the pages are loaded. It deprecated and you need at least one image in the html but if you can manage this (you could place transparent 1px*1px image) it's a good solution.
wv.setPictureListener(new PictureListener() {
#Override
public void onNewPicture(WebView view, Picture picture) {
// some code here
}
}
});

My Android HTML application is losing values stored in localStorage when it shuts down. Anyone else see this issue?

I have a native Android 2.1 application that hosts a web view. I load up a site that contains javascript that uses the LocalStorage feature. When the application is running localStorage works fine. When some users exit the application and restart it, all the values are gone. I'm not seeing this problem in my Motrola Droid or Sprint EVO, but there is a report of users in the field with this issue.
Does anyone know what I am missing? I'm setting the following flag to true.
settings.setDomStorageEnabled(true);
To make the local storage work for your own WebView in Android, you need to make sure the WebView is using the correct file, and the local storage is enabled like this:
String packageName = "com.dongshengcn.android";
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDatabaseEnabled(true);
settings.setDatabasePath("/data/data/"+packageName+"/databases");
settings.setDomStorageEnabled(true);
Where "com.dongshengcn.android" should be replaced with your own android app pacakge name.
Just for complete the previous responses which did not allow to resolve the issue in my case.
I'm working with Android 4.1.1. My app is using local storage within a Webview and I was getting the same issue as in the original question: the local storage works fine until I kill the app. In this case, the data was lost.
By inspiring me from previous responses, and especially from #diyism, I was able to solve my issue with this:
String databasePath = this.getApplicationContext().getDir("databases", Context.MODE_PRIVATE).getPath();
settingsMenu.setDatabasePath(databasePath);
In fact, as written in the setDatabasePath() documentation: to function correctly, this method must be called with a path to which the application can write.
setDatabasePath() method was deprecated in API level 19. I advise you to use storage locale like this:
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
}
only need these two lines:
this.getSettings().setDomStorageEnabled(true); //enable to use "window.localStorage['my']='hello1'", in webview js on >= android 2.0
this.getSettings().setDatabasePath("/data/data/"+this.context.getPackageName()+"/databases/"); //if no set or wrong path, variables disappear on killed
// Confimed on android 2.1 emulator
// enable javascript localStorage
WebSettings webSettings = myWebView.getSettings();
webSettings.setDomStorageEnabled(true); // localStorage
// eg if your package
// package www.myapp.whatever;
// eg webSettings.setDatabasePath("/data/data/www.myapp.whatever/databases/");
webSettings.setDatabasePath("/data/data/packagename/databases/");
this works

Categories

Resources