这两天做一个小项目时,遇到了一个问题,项目是用一个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);