Android WebView设置支持LocalStorage

遇到这样一个问题:

在webview中加载一个网页,这个网页要从网络上获取数据的。然后它需要调用localStorage将文件存储。在电脑浏览器端,微信端,各种浏览器测试都可以,但是,放到我的webview中的时候就不行了!
网页大概就是这么一个网页,注意看第18和31行,第18行是预留的位置(前端不是很懂,大概就是这个意思吧),然后第31行的代码将东西放置到手机上面,就是这个操作,如果你没有对webview进行设置的时候,webview在加载这个localStorage的时候就会报错,类似这样的错误:Uncaught TypeError: Cannot call method 'setItem' of null。(这个东西你必须得通过log才能看到,webview还是会给你默默的加载,即使错了也是默默的。。)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>首页</title>
<meta name="viewport" content="width=device-width,initial-scale=1"> 
<!--<link type="text/css" rel="stylesheet" href="css/index.css" >
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>-->
<script src="js/zepto.min.js"></script>
.............
</head>
<body>
...............
<div class="box">
 <!--顶部-->
 <div class="top">
 <p id="addr"></p>
 <span>首页</span>
 <b><a href="#"><img src="images/search.png"></a></b>
 
 </div>
...............
<script>
................
 $(function(){
 var data = '{"code":"php","item":"1","function":"index"}';
 $.post("http://192.168.1.199/AppServer/index.php",{data:data},function(date){
 var indexdate = eval("("+date+")");
 var weather = indexdate['data'].cityname;
 [v_qing]localStorage[/v_qing].setItem("CityName",indexdate['data'].cityname);
 $('#addr').html(localStorage.getItem("CityName"));
 var pro=indexdate['pro_json'];

................
</script>
</body>
</html>

解决方法

对你的webview设置如下代码:
mWebView.getSettings().setDomStorageEnabled(true);   
mWebView.getSettings().setAppCacheMaxSize(1024*1024*8);  
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();  
mWebView.getSettings().setAppCachePath(appCachePath);  
mWebView.getSettings().setAllowFileAccess(true);  
mWebView.getSettings().setAppCacheEnabled(true);

标签

因为这个错误比较难找,我从中午遇到这个问题,然后就开始找解决的办法,我搜了不少关键字,最后才找到了这个解决的方法。所以把我查找用的关键字也都列出来,默默的放到最后,如果有别的同学也遇到这样的问题,可以尽快的找到答案。

android webview script 结尾

android webview body中的script无法解析

Uncaught TypeError: Cannot call method 'get' of null

Java中statci与{}与构造方法的一种使用技巧 2015-09-01
【转载】真正的无密码登陆win7&修改密码&激活系统管理员,免PE! 2015-09-19

评论区