Local storage


Published on

Published in: Technology
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Local storage

  1. 1. HTML 5 API: Documentation<br />http://www.whatwg.org/specs/web-apps/current-work/multipage/<br />http://dev.w3.org/html5/<br />
  2. 2. localStorage,sessionStorageAND YOU!<br />DOM Storage:<br />
  3. 3. DOM Storage: Why?<br />Minimize HTTP Requests by not submitting unnecessary requests or statefullness<br />Store data in browser across tabs, windows, and sessions<br />Maintain functionality with unreliable connection by queuing data on reconnect <br />Great for mobile web apps<br />Save user preferences<br />Save session statefulness<br />
  4. 4. DOM Storage: Browser Support<br />Firefox 3.5, Safari 4, IE8, Chrome 4+, Opera 10.5: HTML5 localStorage; these modern browsers all support the core localStorage functionality defined in the HTML5 draft.<br />
  5. 5. DOM Storage: Browser Support(cont’d)<br />Firefox 2.x and 3.0: Gecko globalStorage, a very early implementation similar to HTML5’s localStorage.<br />Safari 3.1 & 3.2: HTML5 Database Storage, because Safari 3.1 and 3.2 don’t support HTML5 localStorage.<br />
  6. 6. DOM Storage: Browser Support(cont’d)<br />IE6, IE7: userData persistence, a rarely used IE feature for associating string data with an element on a web page and persisting it between pageviews.<br />Google Chrome Pre 4: Gears Database API, pre-installed into into earlier versions of Chrome<br />
  7. 7. Storage Objects<br />“Each domain and subdomain has its own separate local storage area. Domains can access the storage areas of subdomains, and subdomains can access the storage areas of parent domains.”<br />- http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx<br />Important  For this origin check, HTTP and HTTPS are considered the same protocol.<br />
  8. 8. Storage Objects (cont’d)<br />Domains:<br />localStorage['example.com'] is accessible to example.com<br />localStorage[‘example.com’] is accessible to www.example.com<br />Subdomains:<br />localStorage['www.example.com'] is accessible to example.com<br />localStorage['www.example.com'] is NOT accessible to mail.example.com<br />
  9. 9. Storage Objects (cont’d)<br />Properties stored as Strings<br />Numbers, Booleans, and Objects must be converted<br />If property name DNE, a key/value pair is automatically created to hold it<br />It appears that all browsers delete local storage objects by deleting cookies<br />IE is limited to only 5MB for localStorage and 5MB for sessionStorage<br />"The current default on iPhone is 5.0 MB. If your database grows beyond this limit, the user will automatically be asked to allow or deny the size increase. If he allows the increase, the database size limit will be upped to 10.MB“- http://building-iphone-apps.labs.oreilly.com/ch05.html#ch05%5Fid35933104<br />
  10. 10. localStorage<br />“The local storage mechanism spans multiple windows and persists beyond the current session. ThelocalStorage attribute provides persistent storage areas for domains. It allows Web applications to store nearly 10 MB of user data, such as entire documents or a user's mailbox, on the client for performance reasons.”<br />- http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx<br />
  11. 11. sessionStorage<br />“Session storage is designed for scenarios where the user is carrying out a single transaction. ThesessionStorage attribute of the window object maintains key/value pairs for all pages loaded during the lifetime of a single tab (for the duration of the top-level browsing context). For example, a page might have a check box that the user selects to indicate that he wants insurance.”<br />- http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx<br />
  12. 12. DOM Storage: API<br />Storage Object<br />localStorage and sessionStorage are both instances of the Storage object<br />Methods<br />clear<br />getItem<br />removeItem<br />setItem<br />Key<br />Properties<br />constructor<br />length<br />remainingSpace(IE Only)<br />
  13. 13. DOM Storage: API Methods<br />getItem: Retrieves the current value associated with the key.<br />value = window.localStorage.getItem(key);<br />setItem: Sets a key/value pair.<br />window.localStorage.setItem(key, value);<br />removeItem: Deletes a key/value pair from the DOM Storage collection.<br />window.localStorage.removeItem(key);<br />clear : Removes all key/value pairs from the DOM Storage area.<br />  window.localStorage.clear();<br />key: Retrieves the key at the specified index in the collection.<br />keyValue = window.localStorage.key(n);<br />
  14. 14. DOM Storage: API Properties<br />constructor: Returns a reference to the constructor<br />In FF, localStorage.constructor!== Storage ??<br />length: Retrieves the length of the key/value list.<br />remainingSpace (IE Only): Retrieves the remaining memory space, in bytes, for the storage object.<br />
  15. 15. DOM Storage: API Properties (cont’d)<br />Getter/setters: key values can be used as properties of localStorage in place of getItem or setItem<br />localStorage.x = ‘hey’<br />// localStorage.getItem(‘x’) === ‘hey’<br />localStorage.setItem(‘x’,’you’);<br />// localStorage.x === ‘you’<br />
  16. 16. Examples<br />http://sammystodos.brandonaaron.net/#/list/0<br />sadf<br />
  17. 17. Client-side SQL: <br />Currently only in Webkit& WebOS<br />Chrome 3+ (3,4 via Gears), Safari 3.1+, iPhone, Palm, Android<br />http://dev.w3.org/html5/webdatabase/<br />“The client-side SQL database in HTML 5 enables structured data storage.”<br />
  18. 18. SQL API: Database Object<br />Methods<br />openDatabase<br />transaction<br />readTransaction<br />changeVersion: Change the DB’s version.<br />Properties<br />version: The DB’s current version.<br />
  19. 19. SQL API: openDatabase<br />window.openDatabase( DatabaseName, DatabaseVersion, DisplayName, EstimatedSize)<br />DatabaseName: non-empty String<br />DatabaseVersion: If not the most recent version, openDatabase will fail.<br />DisplayName: any valid String (can be empty)<br />EstimatedSize: an estimated size in bytes<br />vardb = openDatabase(“DallasJS", “1.0", “DallasJS’ sweet DB", 1024*1024);<br />
  20. 20. SQL API:transaction & readTransaction<br />db.transaction(transactionCallback, errorCallback)<br />db.transaction(function(tx) { // EXECUTE SQL CODE VIA tx HERE}, function(e) { alert(tx,e);});<br />The SQLTransactionObject has only method: executeSql<br />
  21. 21. SQL API: executeSql<br />transaction.executeSQL( SQLStatement, SQLParameters, ResultsetCallback, ErrorCallback);<br />SQLStatement: A valid SQLite statement<br />SQLParameters: Array of values<br />“Replace each ? placeholder with the value of the argument in the arguments array with the same position.“<br />ResultsetCallback: Method to handle the returned results<br />ErrorCallback: Method to handle a failed execution<br />
  22. 22. SQL API: executeSql (cont’d)<br />db.transaction(function(tx) {<br />tx.executeSql("SELECT * FROM MyTb WHERE id = ?”,[1],function(tx,SQLResultSet) { console.log(result.rows.item(0)['id']);});<br />});<br />
  23. 23. SQL API: SQLResultSet<br />Properties<br />insertId: The id of the of the inserted row.<br />rowsAffected: Number of rows affected by the statement.<br />rows: The resulting data list.<br />
  24. 24. SQL: Examples<br />http://webkit.org/demos/sticky-notes/index.html<br />db.transaction(function(tx) {tx.executeSql("CREATE TABLE t1 (t1key INTEGER PRIMARY KEY,dataTEXT,numdouble,timeEnter DATE); INSERT INTO 't1' VALUES(1, 'This is sample data', 3, NULL); INSERT INTO 't1' VALUES(2, 'More sample data', 6, NULL); INSERT INTO 't1' VALUES(3, 'And a little more', 9, NULL);");});<br />
  25. 25. Cache Manifest<br />“The mechanism for ensuring Web applications are available even when the user is not connected to their network is the manifest attribute on the html element.”<br />Build WebApp in the form of HTML, CSS, JS, IMG files, etc…<br />You don’t need to include the current HTML file<br />Add link to manifest in html<html manifest=“example.manifest”><br />Make manifest file with MIME type “text/cache-manifest” with paths to resources to be cached:<br />
  26. 26. Cache Manifest: Example<br />CACHE MANIFEST<br /># versionNumber<br />CACHE<br />example.html<br />example.css<br />example.js<br />example.png<br />FALLBACK: * /sorry-i-am-offline.html<br />#give 404 page for all non-cached items when offline<br />NETWORK: /important.html # never cache<br />
  27. 27. Cache Manifest: Events<br />checking: Fired whenever a manifest is present, regardless if page has been visited.<br />downloading: If this cache manifest has never been seen before.<br />progress: Fired during downloading phase giving updates regarding progress.<br />cached: Fired on completion. WebApp is now fully cached<br />noupdate: Fired if cache manifest has been seen, but is not new.<br />downloading & progress: See above.<br />updateready: New manifest has been cached, but your current app is not utilizing it yet.<br />error: 404, 410, Failed to download manifest or a resource<br />obsolete: The manifest was found to have become a 404 or 410 page, so the application cache is being deleted.<br />
  28. 28. Cache Manifest:applicationCache Object<br />The application cache automatically updates only if the manifest file changes. It does not automatically update if resources listed in the manifest file change <br />applicationCache.status: 0-5, corresponds with the following:<br />UNCACHED // === 0<br />IDLE // === 1<br />CHECKING // === 2<br />DOWNLOADING // === 3<br />UPDATEREADY // === 4<br />OBSOLETE // === 5<br />applicationCache.update()<br />applicationCache.swapCache()<br />
  29. 29. Cache Manifest: iPhone EX<br />http://www.technetra.com/2009/08/17/countdown-html5-cache-version/<br />
  30. 30. Are we Offline?<br />“The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail)...”- http://www.whatwg.org/specs/web-apps/current-work/#offline<br />navigator.onLine === true<br />window.addEventListener('online',function(){console.log(‘We’re online!');},true);<br />window.addEventListener(‘offline',function(){console.log(‘We’ve lost power!');},true);<br />
  31. 31. Additional Citations<br />http://html5demos.com/drag<br />http://www.w3.org/TR/webstorage/<br />http://dev.w3.org/html5/<br />https://developer.mozilla.org/en/dom/storage<br />http://www.sqlite.org/docs.html<br />http://www.w3.org/TR/2008/WD-html5-20080610/structured.html<br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.