Chisom Kanu
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Cookies In JavaScript ## Introduction Have you ever wondered how websites remember your login information, shopping cart contents, and other preferences? The answer is cookies. [Cookies](https://policies.google.com/technologies/cookies?hl=en-US) play an important role in enhancing the user experience on websites by storing small pieces of information on the user's device. This information helps websites remember user preferences and activities, making subsequent visits more personalized. Cookies are like little notes that websites leave on your computer when you visit them. These notes contain small information about your visit, such as username, language preference, or the items you added to your shopping cart. They are like a helpful memory for the website. When you go to a website, it is like having a conversation. You tell the website your name, what language you prefer, and what you are interested in. The website then writes these details in a cookie and keeps them safely on your device. And in the world of web development, JavaScript helps make these cookies work. This article will explain the types of cookies, working with cookies in [JavaScript](https://www.w3schools.com/js/), when to use cookies, and the best practices. ## Types of Cookies Cookies come in different types, each serving a unique purpose to enhance your browsing experience. Understanding the types of cookies helps you comprehend how websites remember your preferences and actions. Let's look at the two main types: 1. Session Cookies: When you visit a website, it gives you a session cookie. This cookie is your short-term memory during your visit to that website. They are stored in the browser's memory and deleted when closed. They last only as long as your session on the website. They are gone once you close your browser, just like erasing the slate after you are done reading. 2. Persistent Cookies: Persistent cookies are like a journal. They record your preferences and actions over a more extended period. When you visit a website, it may give you a persistent cookie that stays with you even after you leave and return later. They remember your preference, ensuring the website recognizes you and customizes your experience based on your previous visits. They can last much longer, defined by an expiration date set by the website. Some can last for years, while others might expire after a few days or weeks. ## When to use Cookies Cookies can be used for different purposes, but they are generally used to improve the user experience and to make websites more efficient. Here are some specific examples of when to use cookies: * To remember login information: Cookies can be used to remember the user's login information so that they don't have to enter it every time they visit the website. It is beneficial for websites that require users to log in frequently, such as email websites and social media websites. * To personalize the user experience: Cookies can be used to track the user's preferences, such as their language and time zone, and to display content that is relevant to the user's interests. For example, a news website might use cookies to track the user's favorite topics and display more articles on those topics. * To keep track of shopping cart contents: It can be used to keep track of the items that a user has added to their shopping cart. It allows users to complete their purchase without having to start over if they leave the website and return later. * To improve website performance: Cookies can be used to cache data and reduce the number of requests that need to be made to the server. It can improve the loading speed of websites and make them more responsive. * To track user behavior: It can track the user's browsing activity across different websites. This information can be used for various purposes, such as targeted advertising and website analytics. ## Attributes Cookies can have a number of attributes that control how the cookie is used and how long it is stored. The most common cookie attributes are: * Name: The name of the cookie. It is an identifier for the cookie. * Value: The value of the cookie. It is the data that is stored in the cookie. * Domain: The [domain](https://en.wikipedia.org/wiki/Domain_name) that the cookie belongs to. This is the website that sets the cookie. * Path: The path on the domain that the cookie is valid for. It is the part of the website that the cookie can be used on. * Expires: The date and time that the cookie expires. After this date and time, the cookie will be deleted from the user's computer. * Secure: Whether the cookie should only be sent over secure connections. The cookie will only be sent when the user is connected to a website over [HTTPS](https://en.wikipedia.org/wiki/HTTPS). * [HttpOnly](https://owasp.org/www-community/HttpOnly): Whether the cookie can be accessed by JavaScript. It helps to protect the cookie from being accessed by malicious websites. ## Working with Cookies in JavaScript Working with cookies in JavaScript can be essential for storing and managing data on the client side. JavaScript can be used to work with cookies in several ways. For example, It can be used to: * Set and create cookies * Retrieve cookie data * Delete cookies ### Setting and Creating Cookies To set or create a cookie, we assign a string to the `document.cookie` property. This string usually contains the cookie name, its value, and optional attributes like expiration date, domain, and path. Setting a Cookie: ```javascript document.cookie = "username=ChisomKanu"; ``` Here, we're setting a simple cookie named "username" with the value "ChisomKanu." However, please note that this cookie is a session cookie, meaning it will be removed when the browser is closed. Setting a Persistent Cookie: ```javascript const expirationDate = new Date(); expirationDate.setDate(expirationDate.getDate() + 7); // Cookie expires in 7 days document.cookie = "username=ChisomKanu; expires=" + expirationDate.toUTCString(); ``` We set a persistent cookie by specifying an expiration date. The cookie will be stored for seven days, even if the browser is closed and reopened. Creating a Cookie Function: To simplify cookie creation and make the process more reusable, you can create a function: ```javascript function setCookie(name, value, daysToExpire) { const date = new Date(); date.setTime(date.getTime() + daysToExpire * 24 * 60 * 60 * 1000); const expires = "expires=" + date.toUTCString(); document.cookie = name + "=" + value + "; " + expires + "; path=/"; } // Usage: setCookie("username", "ChisomKanu", 7); // Cookie will expire in 7 days ``` The `setCookie` function takes the cookie's name, value, and the number of days it should persist. It calculates the expiration date and sets the cookie accordingly. ### Retrieving Cookie Data Let's break down the process of retrieving cookie data into a step-by-step approach: * Accessing `document.cookie`: To start, we will access the `document.cookie` property, which contains all the cookies for the current document. * Splitting the Cookie String: Then split the `document.cookie` string into individual key-value pairs using the ``.split('; ')`` method. This method separates the cookies based on the semicolon and space. * Creating a Cookie Object: We then create a JavaScript object to store the cookie data. Each key-value pair extracted from the cookie string is added as a property to this object. * Looping Through Cookies: We iterate through the array of key-value pairs and further split each pair into its cookie name and value using ``.split('=')``. * Populating the Cookie Object: We populate the cookie object with the cookie names as keys and their respective values as values. Let's put the steps into action with a code example: ```javascript function getCookies() { const cookies = document.cookie.split('; '); const cookieData = {}; for (let cookie of cookies) { const [name, value] = cookie.split('='); cookieData[name] = decodeURIComponent(value); } return cookieData; } const cookies = getCookies(); console.log(cookies); ``` The `getCookies` function splits the cookie string into an array of individual cookies using ``.split('; ')``. We initialize an empty object `cookieData` to store the cookie key-value pairs. Using a `for` loop, we iterate through each cookie in the array. For each cookie, we split the name and value using ``.split('=')``. We also use `decodeURIComponent` to decode any special characters in the cookie value. Then, we populate the `cookieData` object with the cookie name as the key and the decoded cookie value as the value. Finally, we return the populated `cookieData` object containing all the cookie information. After retrieving the cookie data as a JavaScript object, we can access individual cookie values using their respective keys. Let's illustrate the process of using the retrieved cookie data with a code example: ```javascript function customizeUserExperience(cookies) { if (cookies.username) { console.log(`Welcome back, ${cookies.username}!`); } else { console.log('Welcome to our website!'); } if (cookies.language) { console.log(`Displaying content in ${cookies.language}.`); // Additional logic to set the website language accordingly } } // Assuming cookies is the cookie object retrieved earlier customizeUserExperience(cookies); ``` The `customizeUserExperience` function takes the retrieved cookie object as an argument. It checks if the `username` cookie exists. If it does, it logs a personalized welcome message. If not, a general welcome message is logged. It also checks if the language cookie exists. If it does, it logs a message indicating the displayed content language. Further logic can be added to set the website language or customize the user interface based on other retrieved cookie values. ### Cookie Deletion Cookie deletion is an important aspect of web development, allowing developers to manage user data and privacy effectively. In JavaScript, cookies can be deleted to enhance user privacy or remove outdated information. When a cookie is deleted, it is removed from the user's device, and the browser will no longer send that cookie to the server. Cookies can be deleted based on various conditions, such as user actions or when certain data is no longer needed. Let's look at the process of deleting cookies using JavaScript: * Accessing `document.cookie`: To start, we access the `document.cookie` property to manipulate the cookie data. * Setting the Expiry Date to the Past: To delete a cookie, we set its expiry date to a date in the past. This tells the browser to remove the cookie. * Setting the Path (if needed): If the cookie was initially set with a specific path, the deletion should use the same path for consistency. Illustration with a code example: ```javascript function deleteCookie(cookieName) { document.cookie = `${cookieName}=; expires=Tue, 10 Oct 2023 00:00:00 UTC; path=/;`; } ``` The `deleteCookie` function takes the cookie name as a parameter. The function then modifies the `document.cookie` property by setting the expiry date of the specified cookie to a date in the past (October 10, 2023). The `path` attribute is set to '/' to ensure the cookie is deleted regardless of its initial path. Some things to keep in mind when deleting cookies: * If you delete a cookie used for authentication, the user will be logged out of the website. * If you delete a cookie that is used for personalization, the user's preferences will be reset. * If you delete all of the cookies for a website, the user will have to log in and set their preferences again the next time they visit the website. ## How to Use DevTools to Examine Cookies Web developers frequently use browser DevTools to inspect and analyze various aspects of their web applications. Cookies, being an essential part of web development, can also be examined using DevTools. It enables developers to verify that cookies are set, read, and deleted as intended. To begin, open your web browser and navigate to the web page for which you want to examine cookies. Once on the webpage, you can open DevTools using one of the following methods: * Right-click and Inspect: Right-click on any element on the page and select "Inspect" or "Inspect Element" from the context menu. * Keyboard Shortcut: Use the keyboard shortcut: Windows/Linux: Ctrl + Shift + I Mac: Command + Option + I Menu: Open the browser menu (usually represented by three vertical dots or lines), go to "More Tools," and then select "Developer Tools." ![](https://hackmd.io/_uploads/B1a2Kg0WT.png) * Navigating to the Application Tab: Once DevTools is open, navigate to the "Application" tab. This tab contains various sections related to application data, including Cookies, Local Storage, Session Storage, and more. ![](https://hackmd.io/_uploads/SJFYsxC-T.png) To examine cookies in DevTools, follow the steps below: * Viewing Cookies In the "Application" tab, look for "Cookies" in the left sidebar. Clicking on it will display all the domains related to the current website. Select a domain to view its associated cookies. The picture below shows the cookies of google.com: ![](https://hackmd.io/_uploads/rkd0Re0Za.png) * Cookie Details Click on a specific cookie to view its details. This includes information such as the cookie name, value, domain, path, expiration, and other attributes. * Filtering Cookies DevTools allows you to filter cookies by domain. It can be useful when dealing with websites that have many cookies. Use the filter option to narrow down the list and focus on specific cookies. * Deleting Cookies To delete a cookie, right-click on the cookie in the list and select "Delete" or use the "Delete" button at the bottom. This action will remove the cookie from the browser. ![](https://hackmd.io/_uploads/Sk8Xb-AWp.png) ## Conclusion In conclusion, It is important to note that not all cookies are created equal. Some cookies are essential for the proper functioning of a website, while others are used for less essential purposes such as tracking and advertising. However, disabling cookies may prevent some websites from functioning properly. Cookies can be a valuable tool for improving the user experience, but they should be used cautiously. Users should be aware of the types of cookies they accept when they visit a website and should have the option to opt out of cookies. Also, disabling cookies may prevent some websites from functioning properly. Websites should have a clear and concise privacy policy that explains how they use cookies. Developers should take steps to protect cookies from being stolen or modified by attackers.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully