Android WebView踩坑集锦(一)

4,815 阅读1分钟

项目背景

原生Android项目中通过 WebView 加载 assets/www 文件夹下的 index.html

ERROR, source file:///android_asset/www/build/vendor.js (1)

Android StudioLog 记录中发现此错误信息,然后通过 Chromeinspect 工具查看到 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);
        }