In JavaScript, you can manipulate cookies through the `document.cookie` property.
Here’s how you can do it:
Create/Update a cookie:
```
document.cookie = ‘username=John Doe’;
```
In this case, ‘username’ is the cookie’s name, and ‘John Doe’ is the value.
By default, the cookie is deleted when the browser is closed. If you want to specify the cookie’s lifespan, you can use the `expires` attribute.
```
document.cookie = ‘username=John Doe; expires=Thu, 20 Jan 2022 12:00:00 UTC’;
```
Reading a cookie:
When you read the `document.cookie` property, it will return all cookies in one string (e.g. ‘username=John Doe; theme=light’):
```
let allCookies = document.cookie;
```
Thus, you may need to parse the string to get the value of the specific cookie you want:
```
function getCookie(name) {
let cookieArr = document.cookie.split(“; “);
for(let i = 0; i < cookieArr.length; i++) {
let c = cookieArr[i].split(‘=’);
if(name == c0) {
return c1;
}
}
return “”;
}
let userName = getCookie(‘username’);
```
Delete a cookie:
To delete a cookie, you just need to set the value of the cookie to an empty string and set the `expires` attribute to a passed date:
```
document.cookie = “username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;”;
```
Secure cookies:
To prevent cookie data from being intercepted or manipulated, the `Secure` and `HttpOnly` attributes can be used.
```
document.cookie = “username=John Doe; Secure; HttpOnly”;
```
- The `Secure` attribute is used to ensure that the cookie can only be sent to the server with an encrypted request over the HTTPS protocol.
- The `HttpOnly` attribute is used to help prevent attacks such as cross-site scripting, since it does not allow the cookie to be accessed via JavaScript. It is only sent to the server.
Remember that cookies are mainly used for tracking and personalisation purposes and can also be blocked by some users or web browsers, so always have an alternative way to manage data.