Android webview 打开本地H5项目(Cocos游戏以及Unity游戏)
webview打开本地Html文件
1.在路径前面加上file://
String filePath="file://"+path;
webView.loadUrl( filePath);
2.打开权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
3.启用JavaScript 设置本地访问权限
webView.getSettings().setJavaScriptEnabled(true);
webSettings.setAllowContentAccess(true);
4.如果js代码访问本地文件出现CORS跨源请求 可以通过重写WebViewClient的shouldInterceptRequest函数拦截请求并替换为本地资源
webView.setWebViewClient(new WebViewClient(){
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
// 获取请求的URL
String url = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
url = request.getUrl().toString();
}
// 检查URL是否符合你想要替换的file域规则
if (url.startsWith("file://")) {
String path=url;
try {
if(path.contains(".jpg")||path.contains(".png")){
Map<String, String> headers = new HashMap<>();
headers.put("Access-Control-Allow-Origin", "*");
InputStream inputStream = new FileInputStream(new File(path));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
WebResourceResponse response= new WebResourceResponse("image/png", "UTF-8", inputStream);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
response.setResponseHeaders(headers);
}
return response;
}
}
else {
} catch (IOException e) {
// 处理异常
e.printStackTrace();
}
}
// 如果不是file域请求,则返回null继续加载
return super.shouldInterceptRequest(view, request);
}
});
5.如果H5项目中用到了Fetch 出现报错Fetch API cannot load 是因为Fetch不支持使用file://访问本地文件, 可以在html文件中处理下
如果是 arraybuffer 可以这样处理
<script>window.fetch=function fetchLocal(url, data) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest
xhr.onload = function () {
resolve(new Response(xhr.response, { status: xhr.status }))
}
xhr.onerror = function () {
reject(new TypeError('Local request failed'))
}
xhr.open('GET', url)
xhr.responseType = "arraybuffer";
xhr.send(null)
})
}</script>
否则可以这样处理下
<script>window.fetch=function fetchLocal(url, data) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest
xhr.onload = function() {
resolve(new Response(xhr.responseText, {status: xhr.status}))
}
xhr.onerror = function() {
reject(new TypeError('Local request failed'))
}
xhr.open('GET', url)
xhr.send(data)
})
}</script>
至此,就可以离线访问本地的Unity,Cocos等H5游戏