L32 - JS Storage
L32 - JS Storage
COS216
AVINASH SINGH
DEPARTMENT OF COMPUTER SCIENCE
UNIVERSITY OF PRETORIA
Local Storage – Overview
A cookie is a variable that is stored by the client’s browser for future use by a website
The cookie can be used locally, or the value can be send to the server
Name comes from “magic cookie” used by Unix programmers, describing a packet
of data that is submitted unchanged
A cookie consists of
A name (required)
A value (required)
An expiration date (optional)
Cookies – Overview
Personalisation
Example: Change theme for website
User tracking
Example: Track user actions
Cookies – Server Communication
Request
Client Server
Response
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie: name=value; Expires=Mon, 18-Mar-
2013 09:20:00 GMT+2
Cookies – Server Communication
Request
Client Server
function getCookie(name)
{
// Get all cookies
// Look for cookie with the same name
// Return the cookie value
}
Cookies – Code
function getCookie(name)
{
var cookies = document.cookie.split(";");
}
Cookies – Code
Note that most modern browsers do not store cookies for local files
If you open a local file (file:///...) the browser will ignore cookies
The website URL must start with http:// or https:// for the browser to store cookies
Cookies – Drawbacks
Very cumbersome to store and retrieve cookies, requires a lot of manual code
Not very secure, due to cookie stealing
No authentication needed to access cookies
Some browsers now block access to cookies from a different domain
Limited storage size of only 4KB
Not the best to store binary data, like profile pictures
Can only store strings, no structured data
Structured data can be stringified and stored as a JSON string
DOM Storage – Overview
Session Storage
Separate storage for each page
Data is cleared when page/tab is closed
Local Storage
Same as session storage
However, data is stored permanently
Persistent even if tab or entire browser is closed
DOM Storage – Benefits
// Store value
localStorage.setItem('key', 'value');
// Retrieve value
var value = localStorage.getItem('key');
DOM Storage – Code
// Store value
sessionStorage.setItem('key', 'value');
// Retrieve value
var value = sessionStorage.getItem('key');
DOM Storage – Code
// Store value
localStorage.setItem('key', JSON.stringify({"number": 1234}));
// Retrieve value
var value = JSON.parse(localStorage.getItem('key'));
This Photo by Unknown Author is licensed under CC BY-NC-ND