Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
JavaScript Basics Course Introduction SoftUni Team Technical Trainers Software University
Advertisements

Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
 Dimitar Ivanov Introduction to programming with microcontrollers.
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Design Patterns: Structural Design Patterns
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
NoSQL Databases NoSQL Concepts SoftUni Team Technical Trainers Software University
Redis Key-Value Database: Practical Introduction
Composer packages Installing and Using Composer, Packagist, Packaging your code Mario Peshev Technical Trainer Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Start Your Own Blog Angel Georgiev Part-time Trainer angeru.softuni-friends.org Software University The Culture of Knowledge Sharing.
Entity Framework Performance SoftUni Team Technical Trainers Software University
Cookies Web Browser and Server use HTTP protocol to communicate and HTTP is a stateless protocol. But for a commercial website it is required to maintain.
Microsoft Azure SoftUni Team Technical Trainers Software University
Svetlin Nakov Technical Trainer Software University
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
JavaScript Best Practices Learn How to Write Better Quality JavaScript Software University Technical Trainers SoftUni Team.
CV Structure, Content, Layout, Formatting, Best Practices SoftUni Team Technical Trainers Software University
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
Controls, Widgets, Grid…
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
Web Development Tools Tools for Front-End Developers Writing HTML and CSS Code SoftUni Team Technical Trainers Software University
Web Fundamentals (HTML and CSS)
ASP.NET SignalR SoftUni Team Technical Trainers Software University
JQuery Overview Unleash the Power of jQuery SoftUni Team Technical Trainers Software University
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Working with Forms in PHP HTTP GET / POST, Validation, Escaping, Input Types, Submitting Arrays, URL Redirecting, PHP Superglobals Svetlin Nakov Technical.
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
CSS Transitions and Animations Animated HTML Elements SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
JavaScript Applications Course Introduction SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
JavaScript Tools Tools for Writing / Editing / Debugging JavaScript Code Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
JavaScript Applications Course Introduction SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Team Work and Personal Skills Course Introduction Angel Georgiev Part-time Trainer Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
State Management Cookies, Sessions SoftUni Team State Management
Caching Data in ASP.NET MVC
Extending functionality using Collections
ASP.NET REST Services SoftUni Team ASP.NET REST Services
Presentation transcript:

Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University

 Cookies: Overview, Structure, Usage  Web Storages  Session Storage  Local Storage  Saving objects in Web Storages  Storage Events  Cookies vs. Web Storages Table of Contents 2

HTTP Cookies How the Cookies Work?

 Cookies are small pieces of data in the Web browser  Sent by the Web server (Web application)  Stored inside the user's Web browser  At each request the browser sends the cookies to the server  Cookies can store only plain text  The size of the cookies can be up to 4KB  Cookies can be read / set by JavaScript What are Cookies? 4

5  Cookies do not authenticate a user  Cookies give a unique identifier to differentiate one user from another What are not Cookies? !=

6 Cookie – How It Works? 1. HTTP Request 2. HTTP Response + Set cookie 3. HTTP Request + cookie 4. HTTP Response Web Client Web Server

 A cookie consists of several parts  A name-value pair that holds the cookie information  The name is used to reach the data stored in the value  The expire date of the cookie  Used to set timeframe for the cookie work  A cookie without an expiration date is removed on browser close event  Path at the server the cookie is good for  Domain the cookie is good for Cookies: Structure 7

 Cookies save some state of the user preferences in the browser  Authenticated to the server once, remember your login  E.g. you login at some site a click "Remember Me"  If someone steals the cookie, he takes your saved credentials  Cookies are sent with the headers of all HTTP requests to the matching server  Cookies keep track of your movements within the site  E.g. remember the theme selection and other preferences Cookies: Usage 8

 Cookies can be accessed from JavaScript  Use document.cookie property  Cookies are not strings, they are read as strings  JavaScript doesn’t have good API to easily work with cookies Working with Cookies from JS document.cookie = 'c1=cookie1; expires=Thu, 30 Apr :44:00 UTC; path=/' document.cookie = 'c2=cookie2; expires=Tue, 29 Apr :11:11 UTC; path=/' console.log(document.cookie); 9

10 Creating Cookies function setCookie(name, value, expires, path, domain) { var cookie = name + '=' + escape(value) + ';'; var cookie = name + '=' + escape(value) + ';'; if (expires) { if (expires) { if(expires instanceof Date) { if(expires instanceof Date) { expires = new Date(); expires = new Date(); } else { } else { expires = new Date(new Date().getTime() + expires = new Date(new Date().getTime() + parseInt(expires) * 1000 * 60 * 60 * 24); parseInt(expires) * 1000 * 60 * 60 * 24); } cookie += 'expires=' + expires.toGMTString() + ';'; cookie += 'expires=' + expires.toGMTString() + ';'; } if (path) { cookie += 'path=' + path + ';'; } if (path) { cookie += 'path=' + path + ';'; } if (domain) { cookie += 'domain=' + domain + ';'; } if (domain) { cookie += 'domain=' + domain + ';'; } document.cookie = cookie; document.cookie = cookie;}

Reading Cookies function readCookie(name) { var nameEQ = name + '='; var nameEQ = name + '='; var allCookies = document.cookie.split(';'); var allCookies = document.cookie.split(';'); for(var i = 0; i < allCookies.length; i += 1) { for(var i = 0; i < allCookies.length; i += 1) { var cookie = allCookies[i]; var cookie = allCookies[i]; while (cookie.charAt(0) == ' ') { while (cookie.charAt(0) == ' ') { cookie = cookie.substring(1, cookie.length); cookie = cookie.substring(1, cookie.length); } if (cookie.indexOf(nameEQ) == 0) { if (cookie.indexOf(nameEQ) == 0) { return cookie.substring(nameEQ.length, cookie.length); return cookie.substring(nameEQ.length, cookie.length); } } return null; return null;} 11

12  You can delete a cookie by  Adding a new empty cookie with the same name and expire date Deleting Cookies function deleteCookie(name) { if(getCookie(name)) { if(getCookie(name)) { createCookie(name, '', -1); createCookie(name, '', -1); }}

Cookies Live Demo

Web Storages Cookies, Local and Session

 Methods and protocols used for storing data in a Web browser  Web storages are improved cookies  Provide a set of key-value pairs  Limited to 5MB capacity in most browsers  Not automatically sent to the server at each HTTP request  Web servers can't directly write to the Web storage  Supported down to IE8 (needs shims for IE7) What is Web Storage? 15

16 Web Storage: How It Works? 1. HTTP Request 2. HTTP Response Web Client Web Server 3. Set data to Web storage via JS

 Web Storages are store data in a user's Web browser  Save a user's settings, so next time the user opens the application, they can be loaded  Two common types of Web Storages  Local Storage  Accessible only from a single document  Session Storage  Accessible only while the document is open  Difference between local and session storage: lifetime and scope  Web storages are part of the HTML5 specification Web Storages 17

Local Storage Storing Local Data in the Web Browser

 Accessible through  document.localStorage  Similar to cookies  Data stored through localStorage is permanent  Closing a browser or a tab does not clear the local storage data  It does not expire and remains stored on the user's PC for long  Can store only strings 19

Local Storage – Example  Accessing the local storage  The same as: // Save data in the local storage localStorage[key] = data; // Read data from the local storage var data = localStorage[key]; localStorage.setValue(key, data); var data = localStorage.getValue(key); 20

Local Storage Live Demo

Session Storage Temporary Hold Data in the Browser Session

 The global object sessionStorage maintains storage area, available for the duration of the page session  Accessible through document.sessionStorage  Similar to local storage, but keeps data only for the session  Can store only strings  Opening a page in a new window or a tab starts a new session  Deleted when the window / tab is closed  Great for sensitive data (e.g. banking sessions) Session Storage: How It Works? 23

function incrementLoads() { if (!sessionStorage.counter) { if (!sessionStorage.counter) { sessionStorage.setItem('counter', 0); sessionStorage.setItem('counter', 0); } var currentCount = parseInt(sessionStorage.getItem('counter')); var currentCount = parseInt(sessionStorage.getItem('counter')); currentCount += 1; currentCount += 1; sessionStorage.setItem('counter', currentCount); sessionStorage.setItem('counter', currentCount); document.getElementById('countDiv').innerHTML = currentCount; document.getElementById('countDiv').innerHTML = currentCount;} Session Storage – Example 24

Session Storage Live Demo

Saving Objects in Web Storages as JSON  Local and session storages can only contain strings  Saving objects, invokes its toString() method  To save objects into web storages, extend the Storage prototype Storage.prototype.setObject = function setObject(key, obj) { this.setItem(key, JSON.stringify(obj)); this.setItem(key, JSON.stringify(obj));}; Storage.prototype.getObject = function getObject(key) { return JSON.parse(this.getItem(key)); return JSON.parse(this.getItem(key));}; 26

Saving Object in WebStorages Live Demo

Storage Event Live Demo on storage Web Storage Web Client function evHandler(ev) { // do something // do something console.dir(ev); console.dir(ev);}

Cookies vs. Local Storage

 Cookies Legacy support Persistent data Expiration date Access server or client-side Sent with every request Can store only 4KB Harder to work with Cookies vs. Local Storage  Local Storage Not supported everywhere Persistent data No expiration date (data is saved permanently) Access only client-side Is not sent with every request Can store 5MB Applied same-origin rules 30

31  For saving client-side data, the local storage wins  If your server needs information from a client, cookies will be a better solution  If you want to save some user preferences, choose local storage Cookies vs Local Storage - Conclusion

32  Cookies – small data, sent on every request  document.cookie  Web Storages – storing data in a web browser  Session Storage – stores data only for session  sessionStorage.setItem / getItem  Local Storage – stores data permanently  localStorage.setItem / getItem  Storage Event  on('storage', handler);  Use local storage when you don’t need data on the server Summary

? ? ? ? ? ? ? ? ? Web Storage and Cookies

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 34  Attribution: this work may contain portions from  "JavaScript Applications" course by Telerik Academy under CC-BY-NC-SA licenseJavaScript ApplicationsCC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg