Interfacing Analog to Digital Data Converters ee3404.pdf
19_JavaScript - Storage_Cookies_students.pptx
1. Syllabus
Introduction: Web Development and Client Side Programming, Protocols Governing Web, Internet Services
and Tools, Client-Server Computing;
HTML: Basic Syntax, Standard HTML Document Structure, Basic Text Markup, Images, Hypertext Links, Lists,
Tables, Forms, HTML5;
CSS: Creating Style Sheets, Levels of Style Sheets, CSS Properties, Style Specification Formats, Selector Forms,
The Box Model, Conflict Resolution;
Javascript: Basics of Javascript, Variables, Arrays and Operators, Functions, Event Handlers, Built-in JS
Objects, Form Validations, Conditional and Loops, Storage and Cookies,Debugging and Testing;
Introduction to AJAX: AJAX and Node.Js Server, The Xmlhttprequest Object, Handling The Response, Jquery,
Passing Data, AJAX Application;
PHP Programming: Introduction to PHP, Creating PHP Script, Running PHP Script, Variables and Constants,
Data Types, Operators, Conditional Statements, Control Statements, Arrays, Functions, Working With Forms
and Databases Connection, Introduction to Web-Server and XAMPP.
1
3. Introduction
Data storage is crucial for creating dynamic, responsive, and
personalized user experiences
common methods to store data
•localStorage
•sessionStorage
•Cookies
4. localStorage
• localStorage is part of the Web Storage API
• provides a way to store data locally within the user's browser
• Data stored using localStorage is persistent across browser sessions, i.e no expiration time
• localStorage data for a document loaded in a "private browsing" or "incognito" session is cleared
when the last "private" tab is closed.
• keys and the values stored with localStorage are always in the UTF-16 string format (two bytes per
character)
• Integer keys are always converted to strings
localStorage.setItem(“myName”, “John”);
const name = localStorage.getItem(“myName”);
localStorage.removeItem(“myName");
localStorage.clear();
5. sessionStorage
• sessionStorage is similar to localStorage but with shorter lifecycle
• A session is created with each page opened in a tab
• Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window
• Duplicating a tab copies the tab's sessionStorage into the new tab
• page session lasts as long as the tab or the browser is open, and survives over page reloads and
restores
• data stored in sessionStorage is cleared when the page session ends (i.e., when the browser tab
is closed).
• sessionStorage creates different objects for different protocols (HTTP, HTTPS, FTP etc..)
// Save data to sessionStorage
sessionStorage.setItem("key", "value");
// Get saved data from sessionStorage
let data = sessionStorage.getItem("key");
// Remove saved data from sessionStorage
sessionStorage.removeItem("key");
// Remove all saved data from sessionStorage
sessionStorage.clear();
6. sessionStorage
// Get the text field that we're going to track
let field = document.getElementById("field");
// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (sessionStorage.getItem("autosave")) {
// Restore the contents of the text field
field.value = sessionStorage.getItem("autosave");
}
// Listen for changes in the text field
field.addEventListener("change", () => {
// And save the results into the session storage object
sessionStorage.setItem("autosave", field.value);
});
7. Cookies
• An HTTP cookie (web cookie, browser cookie) is a small piece of data that a
server sends to a user's web browser.
• Browser stores the cookie and sends it back to the same server with later
requests
• Useful in identifying if two requests come from the same browser—keeping a
user logged in
• remembers stateful information for the stateless HTTP protocol
• Purposes of Cookies
◦ Session management: Logins, shopping carts, game scores, or
anything else the server should remember
◦ Personalization: User preferences, themes, and other settings
◦ Tracking: Recording and analyzing user behavior
8. Cookies
• Client sends a HTTP request
• Server responds with one or more set-cookie headers data and n HTTP cookie
(web cookie, browser cookie) is a small piece of data that a server sends to a
user's web browser.
• browser stores the cookie and sends it with requests made to the same server
inside a Cookie HTTP header
9. Cookies
Cookies can have expiration time
Set-cookie header format
Set-Cookie: <cookie-name>=<cookie-value>
Ex: Server sending 2 cookies
HTTP/2.0 200 OK
Content-Type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry
Client sending cookies to server with a request
GET /sample_page.html HTTP/2.0
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry
10. Cookies: Lifetime
Permanent cookies: are deleted at a date specified by the Expires (GMT String format)
attribute or after a period prescribed by the Max-Age (number of seconds) attribute.
If both Expires and Max-Age are set, Max-Age has precedence.
Session cookies – cookies without a Max-age or Expires attribute
Session cookies are deleted when the current session ends.
The browser defines when the "current session" ends
some browsers use session restoring when restarting.
Set-Cookie: id=a3fWa; Expires=Thu, 31 Oct 2021 07:28:00 GMT;
Set-Cookie: id=a3fWa; Max-Age=2592000
11. Cookies: Secure and HttpOnly
A cookie with the Secure attribute is only sent to the server with an encrypted request
over the HTTPS protocol
Secure cookies are never sent with unsecured HTTP (except on localhost).
Anyone with access to the client's hard disk or JavaScript can read and modify the cookies
To prevent access to cookies fro JavaScript, HttpOnly attribute is used
Set-Cookie: id=a3fWa; Expires=Thu, 21 Oct 2021 07:28:00 GMT;
Secure; HttpOnly
12. Cookies: Domain and Path attributes
• The Domain attribute of a cookie specifies which server can receive that cookie.
◦ Presence of Domain attribute:
cookies are available on main domain and its subdomains.
Ex: Domain=mozilla.org,
cookies are available on mozilla.org and its subdomains like
developer.mozilla.org
◦ Absence of Domain Attribute:
cookies are available only on main domain
• Invalid domain must be rejected by the browser
◦ Ex: following cookie sent by originalcompany.com must be rejected
◦ Set-Cookie: qwerty=219ffwef9w0f; Domain=somecompany.co.uk
• The Path attribute indicates a URL path that must exist in the requested URL in order to
send the Cookie.
◦ The %x2F ("/") character is considered a directory separator,
◦ Ex: Path=/docs, the matching request paths are
◦ /docs /docs/ /docs/Web/ /docs/Web/HTTP
13. Cookies: Domain and Path attributes
• The Path attribute indicates a URL path that must exist in the requested URL in order to
send the Cookie.
• If the Path attribute is not set, its default value is computed from the path of the URI that
set the cookie
◦ If the path is empty, does not start with "/", or contains no more than one "/" character, then the default
value for Path is "/".
◦ Ex: https://example.org or https://example.org/ the path is “/”
◦ Otherwise, the default value for Path is the path from the start up to but not including the final "/"
character
◦ Ex: https://example.org/a/b/c, Path would be "/a/b"
14. Cookies: SameSite attribute
• A site is defined by a registered domain name and a scheme (http or https)
◦ Ex: https://jaipur.manipal.edu/
• The SameSite attribute lets servers specify whether/when cookies are sent with cross-site
requests.
• Three values are set for the SameSite attribute
◦ Strict: browser only sends the cookie with requests from the cookie's origin site
◦ Ex: Cookies from https://jaipur.manipal.edu/ are sent only to https://jaipur.manipal.edu/
◦ Lax: Similar to Strict but user can reach origin page by navigation (or redirection)
◦ Doesn’t work with cross-site requests (Ex: accessing images or resources)
◦ Ex: Navigation to https://jaipur.manipal.edu/ via Google search
◦ manipal.edu home page requesting an image from https://images.google.com/ is a cross-site request
◦ None: Cookies are sent on both originating and cross-site requests, but only in secure contexts
◦ if SameSite=None then the Secure attribute must also be set
• If no SameSite attribute is set, the cookie is treated as Lax (default value)
Set-Cookie: mykey=myvalue; SameSite=Strict
16. Cookies: Creation
document.cookie = "yummy_cookie=choco";
document.cookie = "tasty_cookie=strawberry";
console.log(document.cookie);
// logs "yummy_cookie=choco; tasty_cookie=strawberry"
Cookies created via JavaScript can't include the HttpOnly flag
Cookies available to JavaScript can be stolen through XSS
HttpOnly attribute prevents XSS attacks
Cookies used for sensitive information (such as authentication) should have a
short lifetime, with the SameSite attribute set to Strict or Lax
17. Cookies
Read all cookies accessible from current session
allCookies = document.cookie;
document.cookie returns a string containing a semicolon-separated list of all
cookies (i.e. key=value pairs)
document.cookie = "name=oeschger; SameSite=None; Secure";
document.cookie = "favorite_food=tripe; SameSite=None; Secure";
function showCookies() {
const output = document.getElementById("cookies");
output.textContent = `> ${document.cookie}`;
}
function clearOutputCookies() {
const output = document.getElementById("cookies");
output.textContent = "";
}
19. Cookies
Writing/Updating a Cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 9999 23:59:59 GMT;
path=/";
cookie attribute values optionally follow the key-value pair, each preceded by a
semicolon separator.
Reading a Cookie
const cookies = document.cookie.split('; ');
const usernameCookie = cookies.find(cookie => cookie.startsWith('username='));
const username = usernameCookie.split('=')[1];
Deleting Cookie
• You can delete a cookie by updating its expiration time to past date or max-age to zero or negative value