Browser BOM
JS Cookies
Working with Cookies
JavaScript cookies store data, with SameSite for security.
What are JavaScript Cookies?
Cookies are small pieces of data stored directly in the user's web browser. They are used to remember information about the user, such as login status, preferences, and other session details. JavaScript can be used to manipulate cookies, allowing developers to enhance user experience by keeping track of user interactions while they navigate a site.
Creating and Setting Cookies
To create a cookie, you set the document.cookie
property with a string that contains the cookie name, value, and optional attributes.
In this example, a cookie named username is created with the value JohnDoe. The cookie is set to expire on December 31, 2023, and is available across the entire domain (path=/
).
Reading Cookies
To read cookies, you access the document.cookie
property, which returns all cookies in a single string, separated by semicolons. You will need to split this string to retrieve individual cookie values.
The getCookie
function retrieves the value of a specified cookie by name. It splits the cookies string and extracts the desired value.
Deleting Cookies
To delete a cookie, you can set its expiration date to a past date. This effectively removes the cookie from the browser.
In this example, the username cookie is deleted by setting its expiration date to January 1, 1970.
Using SameSite Attribute
The SameSite
attribute is an important security feature that helps mitigate the risk of cross-site request forgery (CSRF) attacks. It can take three values: Strict
, Lax
, or None
.
- Strict: Cookies will only be sent in a first-party context (not sent with requests initiated by third-party websites).
- Lax: Cookies are not sent on normal cross-site subrequests (like images or iframes), but are sent when a user navigates to the URL from an external site (this is the default behavior).
- None: Cookies will be sent in all contexts, including cross-origin requests, but the cookie must be secure (i.e., sent over HTTPS).
This example sets a SameSite attribute to Lax for the username cookie, with the Secure flag to ensure it is only sent over HTTPS connections.
Browser BOM
- Previous
- Timing
- Next
- Clipboard API