Science Knowings: HTML Course For Social Media

HTML Cookies

Introduction to Cookies

Welcome to our session on HTML Cookies! In this session, we'll explore the basics of cookies and their role in web development.

Cookies are small pieces of data stored on a user's device by web servers. They are used to track user preferences, sessions, and other information.

Session Cookies vs Persistent Cookies

Session Cookies:

  • Expire when the browser is closed.
  • Used to store temporary data, such as shopping cart contents.

Persistent Cookies:

  • Have a specified expiration date or no expiration at all.
  • Used to store long-term data, such as login information.

HTTP Cookies vs Web Storage

HTTP Cookies:

  • Sent in the HTTP header.
  • Limited storage capacity (4KB per cookie).
  • Accessible by the server that set them.

Web Storage:

  • Stored locally on the user's device.
  • Larger storage capacity (5MB).
  • Accessible by JavaScript, not the server.

Creating Cookies

To create a cookie, use the document.cookie property:

document.cookie = 'name=value';

Setting Cookie Values

You can set multiple values for a single cookie by separating them with semicolons:

document.cookie = 'name=John; age=30';

Getting Cookie Values

To get the value of a cookie, split the document.cookie string:

const cookieValue = document.cookie.split('=')[1];

Modifying Cookies

To modify an existing cookie, simply set its value again:

document.cookie = 'name=newValue';

Deleting Cookies

To delete a cookie, set its expiration date to a past date:

document.cookie = 'name=; expires=Thu, 01 Jan 1970 00:00:00 GMT';

Using Cookies Responsibly

Use cookies only when necessary.

Inform users about the use of cookies.

Follow privacy regulations, such as GDPR.

Security Concerns

Cookies can be vulnerable to attacks, such as:

  • Cross-site scripting (XSS)
  • Cookie theft

Use secure protocols (HTTPS) and consider using HttpOnly and SameSite attributes to mitigate risks.

Best Practices

  • Use clear and concise names for cookies.
  • Set appropriate expiration dates.
  • Use secure protocols and attributes.
  • Test cookies thoroughly in different browsers.

Cookies and GDPR

The General Data Protection Regulation (GDPR) imposes strict rules on the use of cookies.

Obtain user consent before setting cookies.

Provide users with clear information about the cookies used.

Cookies in Third-Party Contexts

Third-party cookies are set by domains other than the one being visited.

Used for advertising, tracking, and analytics.

Can be blocked by privacy settings.

Next Up: HTML Web Workers

In the next session, we'll learn about HTML Web Workers, a powerful tool for parallel processing in web applications.

Follow us to stay updated on the latest web development technologies!