一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

cookie解决微信不能存储localStorage的问题

时间:2026-09-15 13:40:01 编辑:袖梨 来源:一聚教程网

本文主要介绍使用cookie解决微信不能存储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())}//取回cookiefunction 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+1c_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');

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

热门栏目