Android webview加载本地html实现跨域访问

来源:互联网 发布:夏普lcd70tx8008a知乎 编辑:程序博客网 时间:2024/06/06 13:34

我们在做一个项目时需要把服务器的网页代码保存到本地节省流量,而里面的数据在服务器使用ajax来获取的,当我们把这个网页用本地wenview打开时,在ajax使用时会报
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help, check http://example.ex.com.
core.min.js:36 XMLHttpRequest cannot load http://【地址】. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://example.ex.com is therefore not allowed access.
查了好多资料有两个解决方案,
1:ajax上使用jsonp 但是必须使用get请求
类似这样

  $.ajax(url, {        data: {          'cityname': '襄阳',          'dtype': 'jsonp',          'key': 'xxxx',          '_': new Date().getTime()        },        dataType: 'jsonp',        crossDomain: true,        success: function(data) {          if(data && data.resultcode == '200'){            console.log(data.result.today);          }        }      });

但是我们这样肯定是不可以的 jsonp使用的数据必须含有callback,当我们按json解析时就会出错,必须让服务器返回jsonp格式的数据
2另一种方法 在android中使用
首先android,访问android WebView private 对象 WebViewCore mWebViewCore,调用 mWebViewCore的private 方法nativeRegisterURLSchemeAsLocal,把http和https忽悠成本地访问。 XMLHttpRequest即可自由跨域。
放代码

try {            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();        }

把代码放在loadurl前 就可以自由的跨域访问啦

0 0
原创粉丝点击