Issue
I am loading a local web application using a webview in Android:
view.loadUrl("https://appassets.androidplatform.net/assets/dist/index.html")
However when I check the current route in my JavaScript it says https://appassets.androidplatform.net/assets/dist/index.html
This makes stuff like routing and file loading kind of a pain - is there a way to set the root of the loaded application, so I can avoid the whole /assets/
?
Solution
Have a look at WebViewAssetLoader the code snippet there does exactly what you need. So you basically just need to forward all the requests which can be handled by the assetsLoader to it, and use the response that it returns.
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");
Answered By - Muhannad Fakhouri
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.