写在前面
在app中嵌入的h5应用,有时需要获取cookie的中的参数,但是通过请求服务端然后返回,确实太麻烦,所以就想通过js直接操作cookie的做法。
JS操作cookie
<script> /* 设置cookie name:键 value:值 expire:过期时间 */ function setCookie(name, value, expire) { var exp = new Date(); exp.setTime(exp.getTime() + expire * 24 * 60 * 60 * 1000 * 1); document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString(); }; //根据键获取cookie function getCookie(name) { var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) return unescape(arr[2]); else return null; }; //删除cookie function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); }; console.log('设置cookie'); setCookie('name', 'wolfy', 2); console.log('设置成功'); console.log('读取cookie'); var result = getCookie('name'); console.log(result); //console.log('删除cookie'); //delCookie('name') </script>
测试结果
总结
js操作cookie在h5应用中还是比较常用的。