公司有个项目,使用Webview加载本地Html,出现了跨域问题,和之前其他项目对比了下,发现webview需要设置配置,配置下就ok了,本篇简单记录下
PS:个人更倾向后台设置下
if (Build.VERSION.SDK_INT >= 16) {
val clazz: Class<*> = mWebView!!.getSettings().javaClass
val method = clazz.getMethod(
"setAllowUniversalAccessFromFileURLs", Boolean::class.javaPrimitiveType
)
method.invoke(mWebView!!.settings, true)
}
try {//本地HTML里面有跨域的请求 原生webview需要设置之后才能实现跨域请求
if (Build.VERSION.SDK_INT >= 16) {
Class<?> clazz = webView.getSettings().getClass();
Method method = clazz.getMethod(
"setAllowUniversalAccessFromFileURLs", boolean.class);
if (method != null) {
method.invoke(webView.getSettings(), true);
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
webView.loadUrl("file:///android_asset/HtmlFileTT/index.html");
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
});
评论区