微信里不能存localStorage怎么办

时间:2016-11-163792举报小编:youjiejie

    微信里不能存localStorage怎么办,在开发基于微信的Web页面时,发现有些机型不能存储信息到localStorage中,或者是页面一旦关闭,存储的信息也失效了。

    用cookie来替代localStorage,存储一些简单的数据。上网查找了一下,发现w3school上已有不错的解决方案。

    设置cookie:

    function setCookie(c_name,value,expiredays)
    {
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
    }
     
    //取回cookie
    function getCookie(c_name)
    {
    if (document.cookie.length>0)
     {
     c_start=document.cookie.indexOf(c_name + "=")
     if (c_start!=-1)
     { 
     c_start=c_start + c_name.length+1 
     c_end=document.cookie.indexOf(";",c_start)
     if (c_end==-1) c_end=document.cookie.length
     return unescape(document.cookie.substring(c_start,c_end))
     } 
     }
    return ""
    }

    示例:

     设置cookie,有效期为365天

    setCookie('username','123',365);

    取回,若cookie失效,将返回空

    getCookie('username');

    经过测试,完全兼容,没有出现问题. 有需要的小伙伴可以参考下,谢谢支持!