@ssports_fe/ssutils
Version:
77 lines (65 loc) • 2.17 kB
JavaScript
function extend() {
let i = 0;
let result = {};
for (; i < arguments.length; i++) {
let attributes = arguments[i];
for (let key in attributes) {
if (attributes.hasOwnProperty(key)) {
result[key] = attributes[key];
}
}
}
return result;
}
/**
*
* @desc 设置Cookie
* @param {String} key
* @param {String} value
* @param {Object} attributes
*/
function setCookie(key, value, attributes) {
if (typeof document === 'undefined') {
return;
}
attributes = extend({
path: '/'
}, attributes);
if (typeof attributes.expires === 'number') {
attributes.expires = new Date(Number(new Date()) + attributes.expires * 864e+5);
}
// We're using "expires" because "max-age" is not supported by IE
attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
try {
let result = JSON.stringify(value);
if (/^[\{\[]/.test(result)) {
value = result;
}
} catch (e) {}
value = encodeURIComponent(String(value))
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
key = encodeURIComponent(String(key))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
.replace(/[\(\)]/g, escape);
let stringifiedAttributes = '';
for (let attributeName in attributes) {
if (!attributes[attributeName]) {
continue;
}
stringifiedAttributes += '; ' + attributeName;
if (attributes[attributeName] === true) {
continue;
}
// Considers RFC 6265 section 5.2:
// ...
// 3. If the remaining unparsed-attributes contains a %x3B (";")
// character:
// Consume the characters of the unparsed-attributes up to,
// not including, the first %x3B (";") character.
// ...
stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
}
let cookieVal = (document.cookie = key + '=' + value + stringifiedAttributes);
return cookieVal;
}
module.exports = setCookie;