local storage

31
HTML 5 API: Documentation http://www.whatwg.org/specs/web -apps/current-work/multipage / http://dev.w3.org/html5 /

Upload: adam-crabtree

Post on 12-May-2015

17.845 views

Category:

Technology


2 download

TRANSCRIPT

Page 2: Local storage

localStorage, sessionStorage

AND YOU!

DOM Storage:

Page 3: Local storage

DOM Storage: Why?

Minimize HTTP Requests by not submitting unnecessary requests or statefullness

Store data in browser across tabs, windows, and sessions

Maintain functionality with unreliable connection by queuing data on reconnect Great for mobile web apps

Save user preferences Save session statefulness

Page 4: Local storage

DOM Storage: Browser Support

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.

Page 5: Local storage

DOM Storage: Browser Support(cont’d)

Firefox 2.x and 3.0: Gecko globalStorage, a very early implementation similar to HTML5’s localStorage.

Safari 3.1 & 3.2: HTML5 Database Storage, because Safari 3.1 and 3.2 don’t support HTML5 localStorage.

Page 6: Local storage

DOM Storage: Browser Support(cont’d)

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.

Google Chrome Pre 4: Gears Database API, pre-installed into into earlier versions of Chrome

Page 7: Local storage

Storage Objects

“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.”- http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx

Important  For this origin check, HTTP and HTTPS are considered the same protocol.

Page 8: Local storage

Storage Objects (cont’d)

Domains: localStorage['example.com'] is accessible

to example.com localStorage[‘example.com’] is accessible to

www.example.com

Subdomains: localStorage['www.example.com'] is accessible

to example.com localStorage['www.example.com'] is NOT

accessible to mail.example.com

Page 9: Local storage

Storage Objects (cont’d)

Properties stored as Strings Numbers, Booleans, and Objects must be converted

If property name DNE, a key/value pair is automatically created to hold it

It appears that all browsers delete local storage objects by deleting cookies

IE is limited to only 5MB for localStorage and 5MB for sessionStorage

"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

Page 10: Local storage

localStorage

“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.”- http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx

Page 11: Local storage

sessionStorage

“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.”- http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx

Page 12: Local storage

DOM Storage: API

Storage ObjectlocalStorage and sessionStorage are both instances of the Storage object

Methods clear getItem removeItem setItem Key

Properties constructor length remainingSpace (IE Only)

Page 13: Local storage

DOM Storage: API Methods getItem: Retrieves the current value associated with the key.

value = window.localStorage.getItem(key);

setItem: Sets a key/value pair. window.localStorage.setItem(key, value);

removeItem: Deletes a key/value pair from the DOM Storage collection. window.localStorage.removeItem(key);

clear : Removes all key/value pairs from the DOM Storage area.   window.localStorage.clear();

key: Retrieves the key at the specified index in the collection. keyValue = window.localStorage.key(n);

Page 14: Local storage

DOM Storage: API Properties constructor: Returns a reference to the

constructor In FF, localStorage.constructor !==

Storage ??

length: Retrieves the length of the key/value list.

remainingSpace (IE Only): Retrieves the remaining memory space, in bytes, for the storage object.

Page 15: Local storage

DOM Storage: API Properties (cont’d)

Getter/setters: key values can be used as properties of localStorage in place of getItem or setItem localStorage.x = ‘hey’▪ // localStorage.getItem(‘x’) === ‘hey’

localStorage.setItem(‘x’,’you’);▪ // localStorage.x === ‘you’

Page 17: Local storage

Client-side SQL:

Currently only in Webkit & WebOS Chrome 3+ (3,4 via Gears), Safari 3.1+,

iPhone, Palm, Android http://

dev.w3.org/html5/webdatabase/ “The client-side SQL database in

HTML 5 enables structured data storage.”

Page 18: Local storage

SQL API: Database Object

MethodsopenDatabase transaction readTransactionchangeVersion: Change the DB’s

version.

Propertiesversion: The DB’s current version.

Page 19: Local storage

SQL API: openDatabase

window.openDatabase( DatabaseName, DatabaseVersion, DisplayName, EstimatedSize ) DatabaseName: non-empty String DatabaseVersion: If not the most recent version,

openDatabase will fail. DisplayName: any valid String (can be empty) EstimatedSize: an estimated size in bytes

var db = openDatabase(“DallasJS", “1.0",

“DallasJS’ sweet DB", 1024*1024);

Page 20: Local storage

SQL API:transaction & readTransaction

db.transaction(transactionCallback, errorCallback) db.transaction(function(tx) {

// EXECUTE SQL CODE VIA tx HERE}, function(e) {

alert(tx,e);});

The SQLTransaction Object has only method: executeSql

Page 21: Local storage

SQL API: executeSql

transaction.executeSQL( SQLStatement, SQLParameters, ResultsetCallback, ErrorCallback ); SQLStatement: A valid SQLite statement SQLParameters: Array of values▪ “Replace each ? placeholder with the value of the

argument in the arguments array with the same position.“

ResultsetCallback: Method to handle the returned results

ErrorCallback: Method to handle a failed execution

Page 22: Local storage

SQL API: executeSql (cont’d)

db.transaction(function(tx) {tx.executeSql(

"SELECT * FROM MyTb WHERE id = ?”,[1],function(tx, SQLResultSet ) {

console.log(result.rows.item(0)['id']);

});

});

Page 23: Local storage

SQL API: SQLResultSet

Properties insertId: The id of the of the inserted

row. rowsAffected: Number of rows

affected by the statement. rows: The resulting data list.

Page 24: Local storage

SQL: Examples

http://webkit.org/demos/sticky-notes/index.html

db.transaction(function(tx) {tx.executeSql("CREATE TABLE t1 (t1key INTEGER PRIMARY KEY,data TEXT,num double,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);");});

Page 25: Local storage

Cache Manifest

“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.”

1. Build WebApp in the form of HTML, CSS, JS, IMG files, etc…

You don’t need to include the current HTML file2. Add link to manifest in html

<html manifest=“example.manifest”>3. Make manifest file with MIME type “text/cache-

manifest” with paths to resources to be cached:

Page 26: Local storage

Cache Manifest: ExampleCACHE MANIFEST# versionNumber

CACHEexample.htmlexample.cssexample.jsexample.png

FALLBACK: * /sorry-i-am-offline.html#give 404 page for all non-cached items when offline

NETWORK: /important.html # never cache

Page 27: Local storage

Cache Manifest: Events

checking: Fired whenever a manifest is present, regardless if page has been visited.

downloading: If this cache manifest has never been seen before. progress: Fired during downloading phase giving updates

regarding progress. cached: Fired on completion. WebApp is now fully cached

noupdate: Fired if cache manifest has been seen, but is not new. downloading & progress: See above. updateready: New manifest has been cached, but your current

app is not utilizing it yet. error: 404, 410, Failed to download manifest or a resource obsolete: The manifest was found to have become a 404

or 410 page, so the application cache is being deleted.

Page 28: Local storage

Cache Manifest:applicationCache Object

The application cache automatically updates only if the manifest file changes. It does not automatically update if resources listed in the manifest file change

applicationCache.status: 0-5, corresponds with the following: UNCACHED // === 0 IDLE // === 1 CHECKING // === 2 DOWNLOADING // === 3 UPDATEREADY // === 4 OBSOLETE // === 5

applicationCache.update() applicationCache.swapCache()

Page 29: Local storage

Cache Manifest: iPhone EX

http://www.technetra.com/2009/08/17/countdown-html5-cache-version/

Page 30: Local storage

Are we Offline?

“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

navigator.onLine === true window.addEventListener('online',function()

{console.log(‘We’re online!');},true); window.addEventListener(‘offline',function()

{console.log(‘We’ve lost power!');},true);