Working with cookies and local storage in JavaScript involves using the document.cookie
property for cookies and the localStorage
object for local storage.
Here's how you can work with cookies:
document.cookie
. The string should have the format name=value; expires=expiry_date; path=path_to_relevant_pages
. For example:document.cookie = "username=John; expires=Fri, 31 Dec 2021 23:59:59 GMT; path=/";
document.cookie
, which returns all the cookies in the form of a string. You can then parse this string to find the value of a specific cookie. Here's an example of reading the "username" cookie:const cookies = document.cookie;
const cookieArray = cookies.split('; ');
for (let i = 0; i < cookieArray.length; i++) {
const cookie = cookieArray[i];
const keyValue = cookie.split('=');
const name = keyValue[0];
const value = keyValue[1];
if (name === "username") {
console.log(value);
break;
}
}
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
Here's how you can work with local storage:
localStorage.setItem(key, value)
method. For example:localStorage.setItem("username", "John");
localStorage.getItem(key)
method. For example:const username = localStorage.getItem("username");
console.log(username);
localStorage.removeItem(key)
method. For example:localStorage.removeItem("username");
Note that both cookies and local storage have limitations such as size restrictions and cross-site scripting (XSS) concerns.