cookie方法封装
方法封装:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | /** * 获取cookie */ export function getCookie(sKey: string): string { if (!sKey) { return null ; } return decodeURIComponent(document.cookie.replace( new RegExp( "(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&" ) + "\\s*\\=\\s*([^;]*).*$)|^.*$" ), "$1" )) || null ; } /** * 设置cookie */ export function setCookie(sKey: string, sValue: string, vEnd: any = 0, sPath: string = '/' , sDomain: string = '' , bSecure: boolean = false ): boolean { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false ; } var sExpires = "" ; if (vEnd) { switch (vEnd.constructor) { case Number: sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd; /* Note: Despite officially defined in RFC 6265, the use of `max-age` is not compatible with any version of Internet Explorer, Edge and some mobile browsers. Therefore passing a number to the end parameter might not work as expected. A possible solution might be to convert the the relative time to an absolute time. For instance, replacing the previous line with: */ /* sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; expires=" + (new Date(vEnd * 1e3 + Date.now())).toUTCString(); */ break ; case String: sExpires = "; expires=" + vEnd; break ; case Date: sExpires = "; expires=" + vEnd.toUTCString(); break ; } } document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "" ) + (sPath ? "; path=" + sPath : "" ) + (bSecure ? "; secure" : "" ); return true ; } /** * 删除cookie */ export function removeCookie(sKey: string, sPath: string, sDomain: string): boolean { if (!hasCookie(sKey)) { return false ; } document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "" ) + (sPath ? "; path=" + sPath : "" ); return true ; } /** * 检查cookie */ export function hasCookie(sKey: string): boolean { if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false ; } return ( new RegExp( "(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&" ) + "\\s*\\=" )).test(document.cookie); } |
使用方法:
1 2 3 4 | cookie.setCookie( 'gymToken' , '66666666' , new Date(86400000 + Date.now())) //添加 cookie.removeCookie( 'gymToken' , '/' , '' ) //删除 console.error( '123123123' ,cookie.getCookie( 'gymToken' )) //取值 console.error( '444444' ,cookie.hasCookie( 'gymToken' )) //判断 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了