What is cookies?
Cookies are small pieces of data that websites store on a user's browser. They are commonly used to remember information about the user or their preferences between different visits to a website. Cookies are sent by the web server to the user's browser and are then stored on the user's device.
Overview to use cookies
Here's a basic overview of how to use cookies in JavaScript:
Setting a Cookie:
To set a cookie, you use the `document.cookie` property. Here's an example of setting a cookie:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2022 12:00:00 UTC; path=/";
In this example, a cookie named "username" is set with the value "John Doe." The `expires` attribute specifies when the cookie will expire.
Getting a Cookie:
To retrieve a cookie, you can read the `document.cookie` property:
const username = document.cookie.replace(/(?:(?:^|.*;\s*)username\s*=\s*([^;]*).*$)|^.*$/, "$1");
This code extracts the value of the "username" cookie.
Deleting a Cookie:
To delete a cookie, you can set its expiration date to a past date. This will effectively remove the cookie.
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Cookie Attributes:
Cookies can have various attributes, such as `expires` (to set an expiration date), `path` (specifying the URL path for which the cookie is valid), `domain` (specifying the domain for which the cookie is valid), and `secure` (if the cookie should only be sent over secure connections).
Here's a simple example using JavaScript to set, get, and delete a cookie:
const username = document.cookie.replace(/(?:(?:^|.*;\s*)username\s*=\s*([^;]*).*$)|^.*$/, "$1"); // Set a cookie . document.cookie = "username=John Doe; expires=Thu, 18 Dec 2022 12:00:00 UTC; path=/"; // Get a cookie const username = document.cookie.replace(/(?:(?:^|.*;\s*)username\s*=\s*([^;]*).*$)|^.*$/, "$1"); console.log("Username:", username); // Delete a cookie document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
Keep in mind that cookies have certain limitations, and privacy concerns should be considered when working with them. Modern web development often uses other technologies like `localStorage` or `sessionStorage` for client-side storage, and server-side storage mechanisms for more sensitive data.
0 Comments
Welcome to our website!