Skip to content

Instantly share code, notes, and snippets.

@hitGovernor
Last active Apr 13, 2020
Embed
What would you like to do?
A simple cookie module, accounts for setting, getting, and removing client-side cookies via JavaScript.
var cookies = {
/**
* @param payload {object}
* @param payload.cookieName {string}
* @param payload.cookieValue {string}
* @param payload.days {=Number} - number of days before cookie expires
* @param payload.sameSite {=string} sameSite setting, default to "None" if not provided
* @param payload.secure {=Boolean} default to not secure
*/
set: function (payload) {
var cookieDomain = document.location.hostname.split(".").slice(-2).join("."),
protocol = document.location.protocol,
sameSite = (payload.sameSite) ? payload.sameSite : "None",
isSecure = payload.secure ? payload.secure : ((sameSite === "None" && /^https/i.test(protocol)) ? "secure" : ""),
// isSecure = payload.secure ? payload.secure : (sameSite === "None") ? "secure" : "",
d = new Date;
d.setTime(d.getTime() + 24 * 60 * 60 * 1000 * payload.days);
document.cookie = payload.cookieName + "=" + payload.cookieValue + ";path=/;domain=" + cookieDomain + ";expires=" + d.toGMTString() + ";SameSite=" + sameSite + ";" + isSecure;
},
/**
* @param cookieName {string}
*/
get: function (cookieName) {
var v = document.cookie.match('(^|;) ?' + cookieName + '=([^;]*)(;|$)');
return v ? v[2] : null;
},
/**
* @param cookieName {string}
*/
remove: function (cookieName) {
this.set({
cookieName: cookieName,
cookieValue: "",
days: -1
});
}
};
@hitGovernor
Copy link
Author

hitGovernor commented Apr 13, 2020

Last update includes handling options for setting secure cookies based on value of sameSite and protocol if not otherwise specified.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment