如何在JavaScript中创建和读取Cookie中的值?
如何在JavaScript中创建和读取Cookie中的值?
Answers:
以下是可用于创建和检索Cookie的功能。
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}
简约且功能齐全的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)
}
toGMTString()
已弃用,请toUTCString()
改用。
=
符号。在这种情况下,功能getCookie
将产生意外的结果。为了避免这种情况,请考虑在内部使用以下箭头函数减小const [n, ...val] = v.split('='); return n === name ? decodeURIComponent(val.join('=')) : r
864e5 = 86400000 = 1000*60*60*24
表示一天24小时的毫秒数。
或纯Javascript:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : ("; expires="+exdate.toUTCString()));
document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0; i<ARRcookies.length; i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Mozilla提供了 简单的框架,框架具有完整的unicode支持,用于读取和写入cookie,以及有关如何使用它的示例。
一旦包含在页面上,您就可以设置Cookie:
docCookies.setItem(name, value);
读取Cookie:
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的document.cookie页面上查看更多示例和详细信息。
这个简单的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 (opts.days) {
opts['max-age'] = opts.days * 60 * 60 * 24;
delete opts.days
}
opts = Object.entries(opts).reduce((str, [k, v]) => `${str}; ${k}=${v}`, '')
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]):
选项支持所有标准cookie选项并添加“天”:
其他答案使用“过期”而不是“最大年龄”来支持较旧的IE版本。此方法需要ES7,因此IE7仍然不可用(这没什么大不了的)。
注意:有趣的字符,例如“ =”和“ {:}”作为cookie值受支持,正则表达式处理前导和尾随空格(来自其他库)。
如果要存储对象,请使用和JSON.stringify和JSON.parse对其进行编码之前和之后,对其进行编辑,或者添加其他方法。例如:
Cookie.getJSON = name => JSON.parse(Cookie.get(name))
Cookie.setJSON = (name, value, opts) => Cookie.set(name, JSON.stringify(value), opts);
对于需要保存{foo:'bar'}之类的对象的人,我分享了@KevinBurke答案的编辑版本。我已经添加了JSON.stringify和JSON.parse。
cookie = {
set: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else
var expires = "";
document.cookie = name + "=" + JSON.stringify(value) + expires + "; path=/";
},
get : function(name){
var nameEQ = name + "=",
ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return JSON.parse(c.substring(nameEQ.length,c.length));
}
return null;
}
}
因此,现在您可以执行以下操作:
cookie.set('cookie_key', {foo: 'bar'}, 30);
cookie.get('cookie_key'); // {foo: 'bar'}
cookie.set('cookie_key', 'baz', 30);
cookie.get('cookie_key'); // 'baz'
我已经多次使用此线程的可接受答案。这是一段很棒的代码:简单且可用。但是我通常使用babel和ES6及其模块,因此,如果您像我一样,请复制以下代码,以使用ES6进行更快的开发
接受的答案被ES6重写为模块:
export const createCookie = ({name, value, days}) => {
let expires;
if (days) {
let date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
} else {
expires = '';
}
document.cookie = name + '=' + value + expires + '; path=/';
};
export const getCookie = ({name}) => {
if (document.cookie.length > 0) {
let c_start = document.cookie.indexOf(name + '=');
if (c_start !== -1) {
c_start = c_start + name.length + 1;
let c_end = document.cookie.indexOf(';', c_start);
if (c_end === -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return '';
};
然后,您可以将其简单地导入为任何模块(路径可能会有所不同):
import {createCookie, getCookie} from './../helpers/Cookie';
这是在JavaScript中获取,设置和删除Cookie的代码。
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/
我用这个对象。值是经过编码的,因此在从服务器端进行读取或写入时必须考虑它。
cookie = (function() {
/**
* Sets a cookie value. seconds parameter is optional
*/
var set = function(name, value, seconds) {
var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : '';
document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/';
};
var map = function() {
var map = {};
var kvs = document.cookie.split('; ');
for (var i = 0; i < kvs.length; i++) {
var kv = kvs[i].split('=');
map[kv[0]] = decodeURIComponent(kv[1]);
}
return map;
};
var get = function(name) {
return map()[name];
};
var remove = function(name) {
set(name, '', -1);
};
return {
set: set,
get: get,
remove: remove,
map: map
};
})();
您可以使用我的cookie ES模块获取/设置/删除cookie。
在head标签中,包含以下代码:
<script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.js"></script>
要么
<script src="https://raw.githack.com/anhr/cookieNodeJS/master/build/cookie.min.js"></script>
现在,您可以使用window.cookie将用户信息存储在网页中。
您的网络浏览器是否启用了cookie?
returns {boolean} true if cookie enabled.
例
if ( cookie.isEnabled() )
console.log('cookie is enabled on your browser');
else
console.error('cookie is disabled on your browser');
设置一个cookie。
name: cookie name.
value: cookie value.
例
cookie.set('age', 25);
得到一个饼干。
name: cookie name.
defaultValue: cookie default value. Default is undefined.
returns cookie value or defaultValue if cookie was not found
例
var age = cookie.get('age', 25);
删除Cookie。
name: cookie name.
例
cookie.remove( 'age' );
readCookie的改进版本:
function readCookie( name )
{
var cookieParts = document.cookie.split( ';' )
, i = 0
, part
, part_data
, value
;
while( part = cookieParts[ i++ ] )
{
part_data = part.split( '=' );
if ( part_data.shift().replace(/\s/, '' ) === name )
{
value = part_data.shift();
break;
}
}
return value;
}
找到cookie值并返回其值后,该操作应该立即中断。我认为双重分割非常优雅。
如果条件为条件,则替换为空白修剪,以确保其正确匹配
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
我已经编写了简单的cookieUtils,它具有创建cookie,读取cookie和删除cookie的三个功能。
var CookieUtils = {
createCookie: function (name, value, expireTime) {
expireTime = !!expireTime ? expireTime : (15 * 60 * 1000); // Default 15 min
var date = new Date();
date.setTime(date.getTime() + expireTime);
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
},
getCookie: function (name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) {
return parts.pop().split(";").shift();
}
},
deleteCookie: function(name) {
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
};
这是来自w3chools的示例。
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}