如何在JavaScript中创建和读取cookie的值?
当前回答
简约且功能齐全的ES6方法:
const setCookie = (name, value, days = 7, path = '/') => {
const expires = new Date(Date.now() + days * 864e5).toUTCString()
document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=' + path
}
const getCookie = (name) => {
return document.cookie.split('; ').reduce((r, v) => {
const parts = v.split('=')
return parts[0] === name ? decodeURIComponent(parts[1]) : r
}, '')
}
const deleteCookie = (name, path) => {
setCookie(name, '', -1, path)
}
其他回答
chrome团队提出了一种新的方式管理Cookie与Cookie存储API异步(可在谷歌chrome从版本87开始):https://wicg.github.io/cookie-store/
今天已经在其他浏览器中使用了它:https://github.com/mkay581/cookie-store
// load polyfill
import 'cookie-store';
// set a cookie
await cookieStore.set('name', 'value');
// get a cookie
const savedValue = await cookieStore.get('name');
这是一个代码获取,设置和删除Cookie在JavaScript。
function getCookie(name) { name = name + "="; var cookies = document.cookie.split(';'); for(var i = 0; i <cookies.length; i++) { var cookie = cookies[i]; while (cookie.charAt(0)==' ') { cookie = cookie.substring(1); } if (cookie.indexOf(name) == 0) { return cookie.substring(name.length,cookie.length); } } return ""; } function setCookie(name, value, expirydays) { var d = new Date(); d.setTime(d.getTime() + (expirydays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = name + "=" + value + "; " + expires; } function deleteCookie(name){ setCookie(name,"",-1); }
来源:http://mycodingtricks.com/snippets/javascript/javascript-cookies/
使用模板文字的非常短的ES6函数。请注意,您需要自己编码/解码这些值,但对于存储版本号等更简单的目的,它可以开箱即用。
const getCookie = (cookieName) => {
return (document.cookie.match(`(^|;) *${cookieName}=([^;]*)`)||[])[2]
}
const setCookie = (cookieName, value, days=360, path='/') => {
let expires = (new Date(Date.now()+ days*86400*1000)).toUTCString();
document.cookie = `${cookieName}=${value};expires=${expires};path=${path};`
}
const deleteCookie = (cookieName) => {
document.cookie = `${cookieName}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;`;
}
Mozilla创建了一个简单的框架,用于读取和写入cookie,并提供了完整的unicode支持以及如何使用它的示例。
一旦包含在页面中,您可以设置cookie:
docCookies.setItem(name, value);
读饼干:
docCookies.getItem(name);
或者删除cookie:
docCookies.removeItem(name);
例如:
// sets a cookie called 'myCookie' with value 'Chocolate Chip'
docCookies.setItem('myCookie', 'Chocolate Chip');
// reads the value of a cookie called 'myCookie' and assigns to variable
var myCookie = docCookies.getItem('myCookie');
// removes the cookie called 'myCookie'
docCookies.removeItem('myCookie');
查看Mozilla文档中的更多示例和详细信息。饼干页面。
这个简单的js文件的一个版本在github上。
ES7,使用正则表达式的get()。基于MDN
const Cookie = {
get: name => {
let c = document.cookie.match(`(?:(?:^|.*; *)${name} *= *([^;]*).*$)|^.*$`)[1]
if (c) return decodeURIComponent(c)
},
set: (name, value, opts = {}) => {
/*If options contains days then we're configuring max-age*/
if (opts.days) {
opts['max-age'] = opts.days * 60 * 60 * 24;
/*Deleting days from options to pass remaining opts to cookie settings*/
delete opts.days
}
/*Configuring options to cookie standard by reducing each property*/
opts = Object.entries(opts).reduce(
(accumulatedStr, [k, v]) => `${accumulatedStr}; ${k}=${v}`, ''
)
/*Finally, creating the key*/
document.cookie = name + '=' + encodeURIComponent(value) + opts
},
delete: (name, opts) => Cookie.set(name, '', {'max-age': -1, ...opts})
// path & domain must match cookie being deleted
}
Cookie.set('user', 'Jim', {path: '/', days: 10})
// Set the path to top level (instead of page) and expiration to 10 days (instead of session)
用法- Cookie。Get (name, value [, options]): Options支持所有标准cookie选项,并增加了“days”:
path: '/' - any absolute path. Default: current document location, domain: 'sub.example.com' - may not start with dot. Default: current host without subdomain. secure: true - Only serve cookie over https. Default: false. days: 2 - days till cookie expires. Default: End of session. Alternative ways of setting expiration: expires: 'Sun, 18 Feb 2018 16:23:42 GMT' - date of expiry as a GMT string. Current date can be gotten with: new Date(Date.now()).toUTCString() 'max-age': 30 - same as days, but in seconds instead of days.
其他答案使用“expires”而不是“max-age”来支持旧的IE版本。这个方法需要ES7,所以IE7已经出来了(这不是什么大问题)。
注意:像“=”和“{:}”这样有趣的字符被支持作为cookie值,regex处理开头和结尾的空白(来自其他库)。 如果您想存储对象,可以在和JSON之前或之后对它们进行编码。stringify和JSON。解析、编辑上面的内容,或者添加另一个方法。例如:
Cookie.getJSON = name => JSON.parse(Cookie.get(name))
Cookie.setJSON = (name, value, opts) => Cookie.set(name, JSON.stringify(value), opts);
推荐文章
- 如何清除所有<div>的内容在一个父<div>?
- 检测用户何时离开网页的最佳方法?
- 当“模糊”事件发生时,我如何才能找到哪个元素的焦点去了*到*?
- React不会加载本地图像
- 如何将Blob转换为JavaScript文件
- 在另一个js文件中调用JavaScript函数
- 如何在svg元素中使用z索引?
- 如何求一个数的长度?
- 跨源请求头(CORS)与PHP头
- 如何用Express/Node以编程方式发送404响应?
- parseInt(null, 24) === 23…等等,什么?
- JavaScript变量声明在循环外还是循环内?
- 元素在“for(…in…)”循环中排序
- 在哪里放置JavaScript在HTML文件?
- 什么时候.then(success, fail)被认为是承诺的反模式?