使用js简单封装一个cookie
时间: 2023-07-20 18:22:43 浏览: 103
js对cookie操作的封装
好的,下面是一个简单的封装 cookie 的 JavaScript 代码:
```javascript
const CookieUtil = {
// 获取指定名称的 cookie 值
get: function (name) {
let cookieName = encodeURIComponent(name) + "="
let cookieStart = document.cookie.indexOf(cookieName)
let cookieValue = null
if (cookieStart > -1) {
let cookieEnd = document.cookie.indexOf(";", cookieStart)
if (cookieEnd == -1) {
cookieEnd = document.cookie.length
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd))
}
return cookieValue
},
// 设置 cookie 值
set: function (name, value, expires, path, domain, secure) {
let cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value)
if (expires instanceof Date) {
cookieText += "; expires=" + expires.toGMTString()
}
if (path) {
cookieText += "; path=" + path
}
if (domain) {
cookieText += "; domain=" + domain
}
if (secure) {
cookieText += "; secure"
}
document.cookie = cookieText
},
// 删除指定名称的 cookie
unset: function (name, path, domain, secure) {
this.set(name, "", new Date(0), path, domain, secure)
}
}
```
使用方法:
```javascript
// 设置 cookie
CookieUtil.set("username", "jack")
// 获取 cookie
let username = CookieUtil.get("username")
// 删除 cookie
CookieUtil.unset("username")
```
希望对你有所帮助!
阅读全文