Skip to content

Instantly share code, notes, and snippets.

@weichou1229
Created September 20, 2017 02:18
Show Gist options
  • Select an option

  • Save weichou1229/6543b2312e6aa23518c34206fefa4b4c to your computer and use it in GitHub Desktop.

Select an option

Save weichou1229/6543b2312e6aa23518c34206fefa4b4c to your computer and use it in GitHub Desktop.
javascript cookie
export class CookieService {
constructor(@Inject(DOCUMENT) public document) {
}
get(cookieName: string) {
const name = cookieName + "=";
const ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
remove(name: string) {
console.log('remove cookie ' + name);
if (this.get(name)) {
console.log('remove cookie ' + name);
document.cookie = name + "=;path=/;domain=" + document.domain + ';expires=Thu, 01 Jan 1970 00:00:01 GMT';
}
}
put(name: string, value: string, days: number) {
if (!days) days = 6;
const dt = new Date();
dt.setTime(dt.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = name + "=" + value + ";expires=" + dt.toUTCString()
+ ';domain=' + document.domain + ';path=/';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment