Android WebView设置缓存供JS调用window.localStorage

本文解决了一个使用WebView加载页面时遇到的问题:无法通过JS代码设置本地存储。问题出现在尝试设置window.localStorage时,因为WebView本地存储未启用。通过正确配置WebView设置,如启用DOM存储并设置应用缓存路径,解决了该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这两天做一个小项目时,遇到了一个问题,项目是用一个webview去加载网页,其中涉及到了保存用户设置的问题,在android手机浏览器和iOS版本中都是可以的,但是在webview中就失效了,点击保存没有反应,于是就去看了下网页的源代码,找到了这一段JS代码,

function SetDefaultFactory(ajaxHost, urlHost, $$, myApp, mainView, page) {
 var storage = window.localStorage;
 switch (page.query.type) {
 case '0':
 $$("#setDefaultArea").css("display", "block");
 $$("#setDefaultEmail").css("display", "none");
 getArea(ajaxHost, myApp, 'selSetDefaultArea');
 $$("#setDefaultOnClick").click(function() {
 storage["defaultArea"]=$$("#selSetDefaultArea").val();
 myApp.alert('设置成功')
 })
 break;
 case '1':
 $$("#setDefaultArea").css("display", "none");
 $$("#setDefaultEmail").css("display", "block");
  
 $$("#setDefaultOnClick").click(function() {
 var emali = $$("#defautltEmail").val();
 if (emali == "") {
 myApp.alert('请输入邮箱')
 return;
 }
 if (emali.indexOf('&') < 0) {
 storage["defaultEmail"]= $$("#defautltEmail").val().replace(/[\;]/g, '&').replace(/[\;]/g, '&');
 myApp.alert('设置成功')
 } else {
 myApp.alert('不能含有特殊字符&')
 }
 });
 //显示默认邮箱
 var defaultEmail =storage["defaultEmail"]; //getCookie('defaultEmail');
 if (defaultEmail != "" || typeof(defaultEmail) != "undefined") {
  
 $$("#defautltEmail").val(defaultEmail);
 }
 break;
 };
 }

 根据JS代码,如果不输入值或者输入&时,是会有alert提示,于是判断应该不是JS代码调用不到的问题。然后看了下Eclipse的log,

12-20 09:45:06.518: I/chromium(12972): [INFO:CONSOLE(9)] "Uncaught TypeError: Cannot set property 'defaultArea' of null", source: 

发现defaultArea为空,于是把问题锁定在了JS代码中红色加粗的那一段,应该是这一行出了问题,查了一下,必须要讲webview的本地缓存设置之后才能给JS调用window.localStorage这个方法,webview的本地缓存设置方法如下:

/*** 打开本地缓存提供JS调用 **/
        webView.getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        webView.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        // This next one is crazy. It's the DEFAULT location for your app's
        // cache
        // But it didn't work for me without this line.
        // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();
        webView.getSettings().setAppCachePath(appCachePath);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAppCacheEnabled(true);

转载于:https://my.oschina.net/WeiKeForeverYoung/blog/808848

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值