quality_frontend/packages/common/javascript/cookie.js

80 lines
2.0 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @description: 获取cookie数据
* @param {String} 对应cookie的Key
* @return: 对应的Key的Value数据
*/
let allCookie = (function () { // 获取全部的cookie
let cookies = {}
let all = document.cookie.replace(/[ ]/g, '') // 获取cookie并将cookie格式化去掉空格
if (all === '') return cookies
let list = all.split(';')
for (let i = 0; i < list.length; i++) {
let cookie = list[i]
let p = cookie.indexOf('=')
let name = cookie.substring(0, p)
var value = cookie.substring(p + 1)
value = decodeURIComponent(value)
cookies[name] = value
}
return cookies
}())
/**
* @description: 存储到cookie下
* @param {String} 缓存数据对应的Key
* @param {data} 缓存数据对应的Value
* @param {maxage} 设置cookie时间
* @param {path} 设置cookie作用域
* @return: undefined
*/
export function cookieSave (key, val, maxage, domain, path) {
allCookie[key] = val
let cookie = key + '=' + encodeURIComponent(val)
if (maxage) cookie += ';max-age=' + maxage
if (domain) cookie += ';domain=' + domain
if (path) cookie += ';path=' + path
document.cookie = cookie
}
/**
* @description: 获取存储到cookie数据
* @param {String} 存储数据对应的Key
* @return: 对应的Key的Value数据
*/
export function cookieGet (key) {
try {
return allCookie[key] || null
} catch (e) {
return ''
}
}
/**
* @description: 删除存储到cookie下的数据
* @param {String} 存储数据对应的Key
* @return: undefined
*/
export function cookieRemove (key) {
try {
if (!(key in allCookie)) return
delete allCookie(key)
document.cookie = key + '=;max-age=0'
} catch (e) {
return ''
}
}
/**
* @description: 清除所有的cookie
* @return: undefined
*/
export function cookieClear () {
try {
let keys = []
for (let key in allCookie) keys.push(key)
for (let i = 0; i < keys.length; i++) {
document.cookie = keys[i] + '=;max-age=0'
}
allCookie = {}
} catch (e) {
return ''
}
}