项目背景
原生 Android 项目中通过 webView 加载 assets/www 文件夹下的 index.html
ERROR, source file:///android_asset/www/build/vendor.js (1)
从 Android Studio 的 Log 记录中发现此错误信息, 然后通过 Chrome 的 inspect 工具查看到 Log 为:
TypeError: Cannot read property 'setItem' of null {stack: (...)
, 解决方案如下:
- // webview 的设置中添加如下代码
- WebSettings settings = webView.getSettings();
- settings.setDomStorageEnabled(true);
跨域问题
假如本地 HTML 文件中使用 ajax 获取数据, 则会遇到跨域问题, 报错的 Log 如下:
XMLHttpRequest cannot load '...'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 500.", source: file:///android_asset/www/index.html (0)
解决方案如下:
- // webview 的设置中添加如下代码
- try {
- if (Build.VERSION.SDK_INT >= 16) {
- Class<?> clazz = webview.getSettings().getClass();
- Method method = clazz.getMethod("setAllowUniversalAccessFromFileURLs", boolean.class);
- if (method != null) {
- method.invoke(vb.getSettings(), true);
- }
- }
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
Cookie 身份认证
Hybrid App 开发少不了认证的问题, 5.0 以上需要开启第三方 Cookie 存储
- if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true);
- }
来源: https://juejin.im/post/5a9f87c5f265da238b7d8cca