Skip to content

Instantly share code, notes, and snippets.

@hitGovernor
Last active April 13, 2020 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hitGovernor/51d403e9958b40b044e410d1b4d92d14 to your computer and use it in GitHub Desktop.
Save hitGovernor/51d403e9958b40b044e410d1b4d92d14 to your computer and use it in GitHub Desktop.
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

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