SlideShare a Scribd company logo
Web Storage

       Dylan Schiemann (@dylans)
       SitePen, Inc.
       HTML5 Code Camp, October, 2010


       © SitePen, Inc. All Rights Reserved

Sunday, October 17, 2010
© SitePen, Inc. All Rights Reserved

Sunday, October 17, 2010
Web Storage Timeline

                   Cookies
                   Flash Storage
                   Dojo Offline/Storage, Google Gears
                   localStorage and sessionStorage
                   window[‘name’] hack
                   WebDatabase and IndexedDB




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
WebSQL API

                   Currently supported by Safari, Chrome, and Opera. Will not
                   be supported by Mozilla.
                   SQL, query-based transactions
                   Asynchronous interactions
                   Editor’s Draft: http://dev.w3.org/html5/webdatabase/
                   Will be easy to use for those well-versed in SQL




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
WebSQL: Open Connection, Create Table

          // Connect to the db
          var db = window.openDatabase("MyDB", "", "My database", 1024);

          // If the db has not been initialized for this user...
          if (db.version != "1") {

                  // User's first visit. Initialize database.
                  db.changeVersion(db.version, "1", function(tx) {

                           // Create "users" table
                           tx.executeSql("CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT);");

                  }, null, function() {

                           // Success!
                           console.log('success!');
                  });
          }
          else {

                  // DB already created, move on....
          }




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
WebSQL: Add Records

          // Connect to the db
          var db = window.openDatabase("MyDB", "1", "My database", 1024);

          // Create a transaction
          db.transaction(function(tx) {

                  // Execute a SQL statement
                  tx.executeSql("INSERT INTO users (name) VALUES (:name);", // sql
                              [{ name: 'Dylan'}], // Object (data)
                              function(tx, results) { // Success!
                                  console.log('Added user. ID: ' + results.insertId,results);
                              },
                              function(tx,e) { // Error!
                                  console.log('Error! ',e);
                              }
                  );
          });




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
WebSQL: Retrieve Records

          // Connect to the db
          var db = window.openDatabase("MyDB", "1", "My database", 1024);

          // Create a transaction
          db.readTransaction(function(tx) {

                  // Search for all users
                  tx.executeSql("SELECT * FROM users", [], function(tx, results) {

                           // Get result rows
                           var rows = results.rows;

                           // For each row
                           for(x = 0; x < rows.length; x++) {

                                    // Get the user information!
                                    var user = rows.item(x);
                                    console.log('Found user: ' + user.name);
                           }
                  });
          });




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
IndexedDB API

                   Actively developed by Mozilla
                   Initial support will begin with Firefox 4 (4b6 has issues)
                   Currently a working draft with the W3C
                   Not SQL-based; JavaScript object storage with indexes
                   Asynchronous interactions
                   Working Draft: http://www.w3.org/TR/IndexedDB/
                   Dojo and Persevere implement it




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
IndexedDB: Open Connection, Create Table

          // Attempt to open a database
          var request = window.indexedDB.open("MyDB","My database"); // DB name, description

          // Add "success" handling
          request.onsuccess = function(event) {

                  // Check to see if the database has been created
                  if(event.result.version != "1") { // not created

                           // Create users table (table name, key, autoincrement?)
                           var tableRequest = db.createObjectStore("users","id",true);

                           // Success!
                           tableRequest.onsuccess = function() {

                                    // Save as created!
                                    db.setVersion("1");
                           };
                  }
          };

          // Account for errors
          request.onerror = function(event) {
              //handle the error
          };


    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
IndexedDB: Create a Store with Data

          // Attempt to open a database
          var request = window.indexedDB.open("MyDB","My database"); // DB name, description

          // Add "success" handling
          request.onsuccess = function(event) {
              // Grab a store
              var objectStore = event.result.objectStore("users");

                  // Add a record
                  objectStore.add({ name: "Dylan", role:"CEO" }).onsuccess(function(){
                      // Success!
                      console.log("Record saved!");
                  });

                  // Add another record
                  objectStore.add({ name: "David", role:"Engineer" }).onsuccess(function(){
                      // Success!
                      console.log("Second record saved!");
                  });

          };




    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010
IndexedDB: Retrieve All Data

          // Attempt to open a database
          var request = window.indexedDB.open("MyDB","My database"); // DB name, description

          // Add "success" handling
          request.onsuccess = function(event) {
              // Open a cursor on the users store
              cursorRequest = event.result.objectStore("users").openCursor();
              // If successful...
              cursorRequest.onsuccess = function(e) {

                           // Grab the cursor
                           var cursor = e.cursor;

                           // If cursor is null, exit
                           if(!cursor) { return; }

                           // Get reference to the object at the cursor position
                           var record = e.cursor.value;

                           // Log object to the console
                           console.log("User: " + record.name + "; Role:   " + record.role);

                           // Continue!
                           cursor.continue();
                  };
          };

    © SitePen, Inc. All Rights Reserved
Sunday, October 17, 2010

More Related Content

What's hot (20)

PDF
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
PDF
Hidden pearls for High-Performance-Persistence
Sven Ruppert
 
PPTX
2015 02-09 - NoSQL Vorlesung Mosbach
Johannes Hoppe
 
PDF
Node.js in action
Simon Su
 
PDF
Couchdb w Ruby'm
Stanisław Wasiutyński
 
PDF
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
TXT
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
Arian Gutierrez
 
PDF
Diving into php
Dan Phiffer
 
PDF
San Francisco Java User Group
kchodorow
 
PDF
Nuxeo - OpenSocial
Thomas Roger
 
KEY
занятие8
Oleg Parinov
 
PDF
Web2py
Lucas D
 
PPTX
Introduction to the new official C# Driver developed by 10gen
MongoDB
 
PDF
Redis the better NoSQL
OpenFest team
 
PDF
Drupal Entities - Emerging Patterns of Usage
Ronald Ashri
 
PDF
2012-03-20 - Getting started with Node.js and MongoDB on MS Azure
Johannes Hoppe
 
KEY
iOS5 NewStuff
deenna_vargilz
 
PDF
最近 node.js 來勢洶洶, 怎麼辦? 別怕, 我們也有秘密武器 RingoJS!
Liwei Chou
 
PPTX
SWORD & ResourceSync - Stuart Lewis
Repository Fringe
 
PPTX
Windows 8 JavaScript (Wonderland)
Christopher Bennage
 
Doctrine MongoDB Object Document Mapper
Jonathan Wage
 
Hidden pearls for High-Performance-Persistence
Sven Ruppert
 
2015 02-09 - NoSQL Vorlesung Mosbach
Johannes Hoppe
 
Node.js in action
Simon Su
 
Couchdb w Ruby'm
Stanisław Wasiutyński
 
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
Tipo virus espia con esto aprenderan a espiar a personas etc jeropas de mrd :v
Arian Gutierrez
 
Diving into php
Dan Phiffer
 
San Francisco Java User Group
kchodorow
 
Nuxeo - OpenSocial
Thomas Roger
 
занятие8
Oleg Parinov
 
Web2py
Lucas D
 
Introduction to the new official C# Driver developed by 10gen
MongoDB
 
Redis the better NoSQL
OpenFest team
 
Drupal Entities - Emerging Patterns of Usage
Ronald Ashri
 
2012-03-20 - Getting started with Node.js and MongoDB on MS Azure
Johannes Hoppe
 
iOS5 NewStuff
deenna_vargilz
 
最近 node.js 來勢洶洶, 怎麼辦? 別怕, 我們也有秘密武器 RingoJS!
Liwei Chou
 
SWORD & ResourceSync - Stuart Lewis
Repository Fringe
 
Windows 8 JavaScript (Wonderland)
Christopher Bennage
 

Similar to Intro to HTML5 Web Storage (20)

PDF
Local Storage
Ivano Malavolta
 
KEY
Intro to IndexedDB (Beta)
Mike West
 
KEY
Week 4 - jQuery + Ajax
baygross
 
PDF
Organizing Code with JavascriptMVC
Thomas Reynolds
 
PDF
Terrastore - A document database for developers
Sergio Bossa
 
PDF
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
SPTechCon
 
PPT
Persistent Offline Storage White
Alexei White
 
PDF
Parse London Meetup - Cloud Code Tips & Tricks
Hector Ramos
 
PDF
Building Your First MongoDB App
Henrik Ingo
 
PDF
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
Robert Nyman
 
PDF
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
PPT
Hibernate
Sunil OS
 
PDF
OrientDB introduction - NoSQL
Luca Garulli
 
PDF
Local data storage for mobile apps
Ivano Malavolta
 
PPTX
Entity Framework Core & Micro-Orms with Asp.Net Core
Stephane Belkheraz
 
PDF
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
PPTX
A Rich Web experience with jQuery, Ajax and .NET
James Johnson
 
PPT
Intorduction of Playframework
maltiyadav
 
PDF
Taking Web Apps Offline
Pedro Morais
 
PPT
Intoduction on Playframework
Knoldus Inc.
 
Local Storage
Ivano Malavolta
 
Intro to IndexedDB (Beta)
Mike West
 
Week 4 - jQuery + Ajax
baygross
 
Organizing Code with JavascriptMVC
Thomas Reynolds
 
Terrastore - A document database for developers
Sergio Bossa
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
SPTechCon
 
Persistent Offline Storage White
Alexei White
 
Parse London Meetup - Cloud Code Tips & Tricks
Hector Ramos
 
Building Your First MongoDB App
Henrik Ingo
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
Robert Nyman
 
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
Hibernate
Sunil OS
 
OrientDB introduction - NoSQL
Luca Garulli
 
Local data storage for mobile apps
Ivano Malavolta
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Stephane Belkheraz
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
A Rich Web experience with jQuery, Ajax and .NET
James Johnson
 
Intorduction of Playframework
maltiyadav
 
Taking Web Apps Offline
Pedro Morais
 
Intoduction on Playframework
Knoldus Inc.
 
Ad

More from dylanks (9)

PDF
Building a Modern JavaScript Framework by James Milner
dylanks
 
PDF
London Ajax User Group Meetup: Vector Graphics
dylanks
 
PDF
Web Vector Graphics
dylanks
 
PDF
Dojo Mobile
dylanks
 
PDF
Intro to WebSockets and Comet
dylanks
 
PDF
HTML5: Toolkits and Gaps
dylanks
 
PDF
Introduction to Canvas and Native Web Vector Graphics
dylanks
 
PDF
London Ajax User Group Meetup: Comet Panel
dylanks
 
PDF
SWDC 2010: Programming to Patterns
dylanks
 
Building a Modern JavaScript Framework by James Milner
dylanks
 
London Ajax User Group Meetup: Vector Graphics
dylanks
 
Web Vector Graphics
dylanks
 
Dojo Mobile
dylanks
 
Intro to WebSockets and Comet
dylanks
 
HTML5: Toolkits and Gaps
dylanks
 
Introduction to Canvas and Native Web Vector Graphics
dylanks
 
London Ajax User Group Meetup: Comet Panel
dylanks
 
SWDC 2010: Programming to Patterns
dylanks
 
Ad

Recently uploaded (20)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 

Intro to HTML5 Web Storage

  • 1. Web Storage Dylan Schiemann (@dylans) SitePen, Inc. HTML5 Code Camp, October, 2010 © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 2. © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 3. Web Storage Timeline Cookies Flash Storage Dojo Offline/Storage, Google Gears localStorage and sessionStorage window[‘name’] hack WebDatabase and IndexedDB © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 4. WebSQL API Currently supported by Safari, Chrome, and Opera. Will not be supported by Mozilla. SQL, query-based transactions Asynchronous interactions Editor’s Draft: http://dev.w3.org/html5/webdatabase/ Will be easy to use for those well-versed in SQL © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 5. WebSQL: Open Connection, Create Table // Connect to the db var db = window.openDatabase("MyDB", "", "My database", 1024); // If the db has not been initialized for this user... if (db.version != "1") { // User's first visit. Initialize database. db.changeVersion(db.version, "1", function(tx) { // Create "users" table tx.executeSql("CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT);"); }, null, function() { // Success! console.log('success!'); }); } else { // DB already created, move on.... } © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 6. WebSQL: Add Records // Connect to the db var db = window.openDatabase("MyDB", "1", "My database", 1024); // Create a transaction db.transaction(function(tx) { // Execute a SQL statement tx.executeSql("INSERT INTO users (name) VALUES (:name);", // sql [{ name: 'Dylan'}], // Object (data) function(tx, results) { // Success! console.log('Added user. ID: ' + results.insertId,results); }, function(tx,e) { // Error! console.log('Error! ',e); } ); }); © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 7. WebSQL: Retrieve Records // Connect to the db var db = window.openDatabase("MyDB", "1", "My database", 1024); // Create a transaction db.readTransaction(function(tx) { // Search for all users tx.executeSql("SELECT * FROM users", [], function(tx, results) { // Get result rows var rows = results.rows; // For each row for(x = 0; x < rows.length; x++) { // Get the user information! var user = rows.item(x); console.log('Found user: ' + user.name); } }); }); © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 8. IndexedDB API Actively developed by Mozilla Initial support will begin with Firefox 4 (4b6 has issues) Currently a working draft with the W3C Not SQL-based; JavaScript object storage with indexes Asynchronous interactions Working Draft: http://www.w3.org/TR/IndexedDB/ Dojo and Persevere implement it © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 9. IndexedDB: Open Connection, Create Table // Attempt to open a database var request = window.indexedDB.open("MyDB","My database"); // DB name, description // Add "success" handling request.onsuccess = function(event) { // Check to see if the database has been created if(event.result.version != "1") { // not created // Create users table (table name, key, autoincrement?) var tableRequest = db.createObjectStore("users","id",true); // Success! tableRequest.onsuccess = function() { // Save as created! db.setVersion("1"); }; } }; // Account for errors request.onerror = function(event) { //handle the error }; © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 10. IndexedDB: Create a Store with Data // Attempt to open a database var request = window.indexedDB.open("MyDB","My database"); // DB name, description // Add "success" handling request.onsuccess = function(event) { // Grab a store var objectStore = event.result.objectStore("users"); // Add a record objectStore.add({ name: "Dylan", role:"CEO" }).onsuccess(function(){ // Success! console.log("Record saved!"); }); // Add another record objectStore.add({ name: "David", role:"Engineer" }).onsuccess(function(){ // Success! console.log("Second record saved!"); }); }; © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010
  • 11. IndexedDB: Retrieve All Data // Attempt to open a database var request = window.indexedDB.open("MyDB","My database"); // DB name, description // Add "success" handling request.onsuccess = function(event) { // Open a cursor on the users store cursorRequest = event.result.objectStore("users").openCursor(); // If successful... cursorRequest.onsuccess = function(e) { // Grab the cursor var cursor = e.cursor; // If cursor is null, exit if(!cursor) { return; } // Get reference to the object at the cursor position var record = e.cursor.value; // Log object to the console console.log("User: " + record.name + "; Role: " + record.role); // Continue! cursor.continue(); }; }; © SitePen, Inc. All Rights Reserved Sunday, October 17, 2010