0% found this document useful (0 votes)
8 views6 pages

Javascript Module 14

The document provides an overview of web storage in JavaScript, detailing localStorage and sessionStorage, including their persistence, scope, storage limits, and usage. It also discusses cookies, their properties, how to set, read, and delete them, along with considerations regarding security and privacy. Additionally, it explains the implications of accepting all cookies on a website and provides code examples for setting cookies for various purposes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views6 pages

Javascript Module 14

The document provides an overview of web storage in JavaScript, detailing localStorage and sessionStorage, including their persistence, scope, storage limits, and usage. It also discusses cookies, their properties, how to set, read, and delete them, along with considerations regarding security and privacy. Additionally, it explains the implications of accepting all cookies on a website and provides code examples for setting cookies for various purposes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Software Training and Placement Center

Web Storages in Javascript

Web storage provides a way to store data locally within the user's browser. It's a key-value storage
mechanism that allows you to save data persistently across sessions without the need for server-side
storage or cookies. There are two types of web storage available in modern web browsers: localStorage
and sessionStorage.

localStorage:
• Persistence: Data stored in localStorage persists even after the browser window is closed.
• Scope: Data stored in localStorage is accessible across browser tabs and windows for the same
origin (domain).
• Storage Limit: The maximum storage size varies across browsers but is typically around 5-10
MB.
• Usage: localStorage is suitable for storing long-term user preferences, settings, or cached data
that should be available across sessions.

Code :
// Store data in localStorage
localStorage.setItem('key', 'value');

// Retrieve data from localStorage


var data = localStorage.getItem('key');

// Remove data from localStorage


localStorage.removeItem('key');

// Clear all data from localStorage


localStorage.clear();

sessionStorage:
• Persistence: Data stored in sessionStorage is only available for the duration of the page session.
It is cleared when the browser tab or window is closed.
• Scope: Data stored in sessionStorage is accessible only within the same browser tab or window
for the same origin (domain).
• Storage Limit: Similar to localStorage, sessionStorage has a storage limit of around 5-10 MB.
• Usage: sessionStorage is suitable for storing temporary data, such as session tokens or data
needed for a single browsing session.

Code :
// Store data in sessionStorage
sessionStorage.setItem('key', 'value');

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

// Retrieve data from sessionStorage


var data = sessionStorage.getItem('key');

// Remove data from sessionStorage


sessionStorage.removeItem('key');

// Clear all data from sessionStorage


sessionStorage.clear();

Advantages of Web Storage:

• Simple API: Web storage provides a simple key-value storage API that is easy to use.
• Client-Side: Data is stored locally on the client-side, reducing server load and improving
performance.
• Persistent Data: localStorage allows you to store data persistently across sessions, while
sessionStorage provides temporary storage for a single session.
• Increased Storage: Web storage typically offers larger storage limits compared to cookies.

Considerations:
• Security: Be cautious when storing sensitive data in web storage, as it is accessible to client-side
scripts and potentially vulnerable to cross-site scripting (XSS) attacks.
• Storage Limitations: Keep in mind the storage limits imposed by browsers and avoid storing
large amounts of data.
• Browser Support: Web storage is supported by modern web browsers, but it's essential to
check for compatibility if targeting older browsers.

Web storage provides a convenient way to store data locally within the user's browser, making it a
valuable tool for building web applications with improved user experiences and performance.

Cookies:
Cookies in JavaScript are small pieces of data stored on the user's browser. They are commonly used to
store information such as user preferences, session tokens, and shopping cart contents. Cookies have
several properties and can be set, read, and deleted using JavaScript.

Setting a Cookie:
You can set a cookie using the document.cookie property. The cookie string should be in the format
"name=value", and you can specify additional attributes like expiration date, path, and domain.

Code :
document.cookie = "username=John";

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

Reading a Cookie:
You can read cookies using the document.cookie property. This property returns a string containing all
the cookies associated with the current document.

Code :
var cookies = document.cookie;
console.log(cookies);

Deleting a Cookie:
To delete a cookie, you can set its value to an empty string and specify an expired date in the past. You
should also ensure that the path and domain match the original cookie.

Code :
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Cookie Attributes:
• Expires: Specifies the expiration date and time of the cookie. Cookies expire and are deleted
from the browser after this date.
• Max-Age: Specifies the maximum age of the cookie in seconds. The cookie is deleted after this
period.
• Domain: Specifies the domain for which the cookie is valid.
• Path: Specifies the URL path for which the cookie is valid.
• Secure: Indicates whether the cookie should only be sent over secure HTTPS connections.
• SameSite: Specifies whether the cookie should be restricted to first-party or same-site requests.

Limitations and Considerations:


• Size Limit: Cookies have a size limit of around 4KB per cookie and a maximum number of
cookies per domain.
• Security: Avoid storing sensitive information in cookies, as they are accessible to client-side
scripts and potentially vulnerable to attacks like cross-site scripting (XSS).
• Privacy Concerns: Users can disable cookies in their browser settings or use browser extensions
to manage cookies, so don't rely on cookies for critical functionality.

Cookies are a useful mechanism for persistently storing small amounts of data on the client-side.
However, they should be used judiciously and in accordance with privacy and security best practices.

Working behind accept all cookies in a website:

If a user clicks "Allow All Cookies" on a website, it typically means that the browser settings are
adjusted to accept all types of cookies from that particular website. Here's what typically happens on
the website:

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

• Full Functionality: All features and functionalities of the website that rely on cookies will work
as intended. This includes features like user authentication, preferences storage, shopping cart
functionality, personalized content delivery, and tracking user behavior for analytics purposes.

• Session Management: Session-related cookies, such as those used for maintaining user login
sessions, will be accepted and utilized. This allows users to stay logged in across pages or visits
to the website.

• Personalization: Cookies used for tracking user preferences and personalization will be
accepted. This enables the website to provide a customized user experience based on the user's
browsing history, behavior, and preferences.

• Third-Party Services: Cookies from third-party services embedded on the website, such as
advertising networks, social media plugins, or analytics providers, will be accepted. This allows
these services to collect data about the user's interactions with the website for their respective
purposes.

• Cross-Origin Requests: Cookies associated with cross-origin resources, such as APIs or external
resources loaded by the website, will be sent along with requests. This facilitates seamless
communication with external services and resources.

Setting cookies as per the above Cookie Preferences when user clicks on “Accept All Cookies”:

To set cookies for user authentication, personalized content delivery, page visits, browsing history, and
other purposes, you can use JavaScript to manipulate the document.cookie property. Here's how you
can set cookies for different purposes:

1. User Authentication:
Code :
// Set a cookie for user authentication
function setAuthCookie(token) {
document.cookie = `authToken=${token}; path=/;`;
}

2. Personalized Content Delivery:


Code :
// Set a cookie for personalized content delivery
function setPersonalizationCookie(preferences) {
document.cookie = `preferences=${JSON.stringify(preferences)};
path=/;`;
}

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

3. Page Visits:
Code :
// Set a cookie for tracking page visits
function setPageVisitCookie() {
var visits = parseInt(getCookie('visits')) || 0;
visits++;
document.cookie = `visits=${visits}; path=/;`;
}

4. Browsing History:
Code :
// Set a cookie for browsing history
function setBrowsingHistoryCookie(history) {
document.cookie = `history=${JSON.stringify(history)}; path=/;`;
}

5. Function to Get Cookie by Name:


Code :
// Function to get cookie value by name
function getCookie(name) {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.startsWith(name + '=')) {
return cookie.substring(name.length + 1);
}
}
return null;
}

Example Usage:
// Set authentication cookie
setAuthCookie('user_token');

// Set personalized content delivery cookie


setPersonalizationCookie({ theme: 'dark', language: 'en' });

// Increment page visits


setPageVisitCookie();

// Set browsing history cookie

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]
Software Training and Placement Center

setBrowsingHistoryCookie(['page1', 'page2', 'page3']);

When setting cookies, ensure that you specify the appropriate attributes such as path,
domain, expires, and secure based on your requirements. Additionally, be mindful of
privacy and security considerations, especially when storing sensitive information in
cookies.

Address : ByteSplash Training and Placement Center, 4th Floor, No 92/9, PR Layout, Marathahalli, Bengaluru, Karnataka, 560037
Mobile : +91 8660803099 / +91 6301062858 , Email : [email protected]

You might also like