Android WebView 设置支持 LocalStorage – 热爱改变生活
我的GitHub GitHub |     登录
  • If you can't fly, then run; if you can't run, then walk; if you can't walk, then crawl
  • but whatever you do, you have to keep moving forward。
  • “你骗得了我有什么用,这是你自己的人生”
  • 曾有伤心之地,入梦如听 此歌

Android WebView 设置支持 LocalStorage

Android组件 sinvader 21546℃ 0评论

遇到这样一个问题:

在 webview 中加载一个网页,这个网页要从网络上获取数据的。然后它需要调用 localStorage 将文件存储。在电脑浏览器端,微信端,各种浏览器测试都可以,但是,放到我的 webview 中的时候就不行了!

网页大概就是这么一个网页,注意看第 18 和 31 行,第 18 行是预留的位置(前端不是很懂,大概就是这个意思吧),然后第 31 行的代码将东西放置到手机上面,就是这个操作,如果你没有对 webview 进行设置的时候,webview 在加载这个 localStorage 的时候就会报错,类似这样的错误:Uncaught TypeError: Cannot call method ‘setItem’ of null。(这个东西你必须得通过 log 才能看到,webview 还是会给你默默的加载,即使错了也是默默的。。)

  1. <!doctype html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title> 首页</title>
  6. <meta name="viewport" content="width=device-width,initial-scale=1">
  7. <!--<link type="text/css" rel="stylesheet" href="css/index.css" >
  8. <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
  9. <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>-->
  10. <script src="js/zepto.min.js"></script>
  11. .............
  12. </head>
  13. <body>
  14. ...............
  15. <div class="box">
  16. <!--顶部-->
  17. <div class="top">
  18. <p id="addr"></p>
  19. <span> 首页</span>
  20. <b><a href="#"><img src="images/search.png"></a></b>
  21. </div>
  22. ...............
  23. <script>
  24. ................
  25. ParseError: KaTeX parse error: Expected '}', got 'EOF' at end of input: (function(){
  26. vardata="code":"php","item":"1","function":"index"; var data = '{"code":"php","item":"1","function":"index"}';.post("http://192.168.1.199/AppServer/index.php",{data:data},function(date){
  27. var indexdate = eval("("+date+")");
  28. var weather = indexdate['data'].cityname;
  29. localStorage.setItem("CityName",indexdate['data'].cityname);
  30. $('#addr').html(localStorage.getItem("CityName"));
  31. var pro=indexdate['pro_json'];
  32.  
  33. ................
  34. </script>
  35. </body>
  36. </html>

解决方法

对你的 webview 设置如下代码:

  1. mWebView.getSettings().setDomStorageEnabled(true);
  2. mWebView.getSettings().setAppCacheMaxSize(1024*1024*8);
  3. String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
  4. mWebView.getSettings().setAppCachePath(appCachePath);
  5. mWebView.getSettings().setAllowFileAccess(true);
  6. mWebView.getSettings().setAppCacheEnabled(true);

标签

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

android webview script 结尾

android webview body 中的 script 无法解析

Uncaught TypeError: Cannot call method ‘get’ of null

¥ 有帮助么?打赏一下~

转载请注明:热爱改变生活.cn » Android WebView 设置支持 LocalStorage


本博客只要没有注明“转”,那么均为原创。 转载请注明链接:sumile.cn » Android WebView 设置支持 LocalStorage

喜欢 (2)
发表我的评论
取消评论
表情

如需邮件形式接收回复,请注册登录

Hi,你需要填写昵称和邮箱~

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址