Developing Offline Web Applications using HTML5
|
|
|
- Alicia Fields
- 9 years ago
- Views:
Transcription
1 White Paper Developig Offlie Web Applicatios usig HTML5 Buildig the applicatios of tomorrow with rich features requires proper uderstadig of the key Web stadards ad frameworks that are emergig today such as HTML5, CSS3, JavaScript, ad jquery. Amog all the latest techologies, HTML 5 is oe of the most- widely accepted techologies, which offers Dyamic user experiece, resposiveess, ad seamless usability across differet browsers ad devices with a lot of attractive features. New features of HTML5 iclude a set of elemets alog with the support for ew Applicatio Programmig Iterface (APIs). HTML5 provides APIs like GeoLocatio, Webstorage, idexdb ad so o. From the list of APIs, the developers ca program their Web applicatios as per their requiremet ad the situatio that best fits to the sceario. Here i this white paper, we will discuss the developmet of Web applicatios that eables the user to have the experiece of the Web, i offlie mode alog with its advatages ad limitatios.
2 About the Author Nilachala Paigrahy The author, Nilachala Paigrahy, is a Systems Egieer, workig with TCS. He has more tha two years of experiece i developig ad maagig Rich Iteret Applicatio (RIA) for various domais. He also has the expertise i User Experiece space. His competecy icludes RIA techologies like Flex, jquery, GWT, ad HTML5. He has worked o differet RIA Web applicatios ad has helped i makig the websites browser compatible ad usable. 2
3 Table of Cotets 1. Itroductio 4 2. Webstorage API 4 Local Storage 5 Sessiostorage 6 Storig ad Retrievig Data 6 Clearig the Data 7 Hadlig Chages 8 Use Cases 8 HTTP Cookies Versus Webstorage 9 3. Offlie Web Applicatio API 9 Architecture of a Offlie Web Applicatio 10 Steps to Follow for Creatig Offlie Web App 11 Browser Support 16 Use Cases Idexeddb API 17 Differece Betwee Relatioal Database Ad Idexeddb 17 Developig a Applicatio Usig Idexdb 17 Browser Support 21 Use Cases Coclusio 22 3
4 Itroductio HTML 5 is the most recet versio of Hyper Text Markup Laguage (HTML), a laguage proposed by Opera Software for Web (World Wide Web) cotet presetatio. HTML is i the process of cotiual developmet sice the day it was created i early 1990s ad HTML5 is the fifth versio of HTML stadard. HTML5 covers the features of HTML4, XHTML 1 ad DOM2HTML. It is a formattig laguage that programmers ad developers use to create documets o the Web. With a umber of ew elemets, attributes, 2D ad 3D graphics, video, audio elemets, localstoragefacility, local SQL database support ad a lot more excitig features, HTML 5 has brought a moumetal chage i World Wide Web. HTML 5 is othig but usig shorthad for cotiuous iovatio i a cliet-cetered applicatio with ew tags o a geeral developmet framework with CSS3 ad JavaScript. It supports both desktop deploymet ad mobile deploymet. Smart phoes like Apple iphoe, Google Adroid, ad phoes ruig Palm WebOS have gaied huge popularity with HTML 5 based rich Web applicatios. HTML 5 cotais a umber of ew ad easily uderstood elemets i various areas. Some of these are as follows: HTML cotrols used i UI Multimedia file supports like video ad audio Database support like local SQL database A umber of ew Applicatio Programmig Iterfaces (APIs) These elemets ca be used i iteractive websites with little customizatio to add a attractive effect ad ehace the performace. Apart from the above features, the beauty of HTML5 comes with the fact that it supports the developmet of Web applicatios that ca be used i offlie mode whe there is ot a prologed ad costat access to the iteret due to usage policies like social etworkig APIs (such as Facebook, Twitter ad so o).to store the data locally ad to allow the applicatios to ru offlie, HTML5 provides three differet APIs ad these are: Web storage: Ca be used for basic localstorage with key-value pairs Offlie storage: Ca be used to save files for offlie use idexdb: Supports relatioal database storage Webstorage API To overcome the limitatios of cookies, Webstorage APIs are beig itroduced i HTML5 that ca be used to store the data locally o the user's machie. This API allows the developers to store the data i the form of KEY-VALUE pairs that ca be accessed by the Web applicatios through scriptig. Web storage works exclusively with cliet side scriptig where data ca be trasmitted to the server o requiremet basis ad a Web server caot write the data to Web storage as well. 4
5 Web storage provides two differet storage areas that differ i scope ad lifetime ad those are: LocalStorage SessioStorage Both localstorage ad sessiostorage objects provide certai useful properties ad methods such as: getitem() Method legth Property remaiigspace Property clear() Method key() Method removeitem() Method setitem() Method : Get the value of item for the key beig passed as the parameter : Retur the legth of the umber of items : Retur the remaiig storage space i bytes, for the storage object : Remove all the key/value pairs from Web Storage : Retrieve the key at specified idex : Remove the specified key/value pair from Web Storage : Set a key/value pair Local Storage The localstorage object is useful whe oe wats to store data that spas across multiple widows ad persists beyod the curret sessio. This object provides persistet storage area for domais. The localstorage keeps the data betwee browser sessios, eve after the browser is closed ad reopeed. if(widow.localstorage){ if (localstorage.pagecout) { localstorage.pagecout=number(localstorage.pagecout) +1; else { localstorage.pagecout=1; else{ documet.write("you are viewig this page " + localstorage.pagecout + " time(s)."); alert("lack of support for localstorage"); 5
6 I the above code, first the browser compatibility is checked. If it foud compatible, the we perform the storage related activities, else the user is iformed about the browser icompatibility. If the browser supports Webstorage, the we are maitaiig a cout that keeps o icreasig wheever the user either refreshes the browser or reloads after closig the widow. Beefits of localstorage object are: Log term data persistece Absece of HTTP overhead of cookies Effective user storig prefereces localstorage objects spaig multiple widows ad persistig beyod the curret sessio. SessioStorage The sessiostorage object stores the data for oe sessio. The data is deleted whe the user closes the browser widow. It allows separate istaces of the same Web applicatio to ru i differet widows without iterferig with each other. Oce, the browser s sessio eds (widow/tab closed), sessiostorage eds.values put ito sessiostorage are oly visible i the widow/tab that created them.opeig page i ew widow or tab starts a ew sessio. if(widow.sessiostorage){ if (sessiostorage.pagecout) { sessiostorage.pagecout=number(sessiostorage.pagecout) +1; else { sessiostorage.pagecout=1; documet.write("you are viewig this page " + sessiostorage.pagecout + " time(s) durig this sessio."); else{ alert("lack of support for sessiostorage"); Storig ad Retrievig Data Ay type of data ca be stored ad retrieved form localstorage usig setitem() ad getitem() methods of the localstorage object. Everythig is stored i the form of strig withi the storage area. It is ecessary to covert the data ito a strig before storig the data ito the storage area. While retrievig the data from the localstorage, we eed to parse the data before puttig that ito appropriate use, if the data is other the Strig type. 6
7 fuctio storedata(){ eid = documet.getelemetbyid("txtempid").value ; eame = documet.getelemetbyid("txtempname").value ; desigatio = documet.getelemetbyid("dddesigatio").value ; if(widow.localstorage){ localstorage.setitem("empid",eid); localstorage.setitem("empname",eame); localstorage.setitem("empdesigatio",desigatio); else { alert("lack of support for localstorage"); The above code first retrieves the values from differet fields ad the stores that ito the storage area usig the setitem() metod that accepts a key ame( empid ) ad a correspodig value (value of the variable eid ) for that. fuctio retrivedata(){ eid = localstorage.getitem("empid"); eame = localstorage.getitem("empname"); desigatio = localstorage.getitem("empdesigatio"); documet.getelemetbyid("txtempid").value = eid ; documet.getelemetbyid("txtempname").value = eame ; documet.getelemetbyid("dddesigatio").value = desigatio ; The above code first retrieves the values from the data storage usig the respective key ames with the help of the getitem() method that accepts the key ame as a parameter ad stores the retrieved value i a variable. The value of the variables are the used to populate the fields of the Web page. Clearig the Data Data stored usig the storage objects ca be deleted by ay oe the followig methods: Usig browser optios Usig the clear ( ) method form the applicatio 7
8 The followig code is used to delete all the cotets form the storage area whe the user clicks the clear butto fuctio cleardata(){ localstorage.clear(); However, if the user wats to delete a specific item form the storage, the he ca use the removeitem() method with the key ame as a parameter that eeds to be deleted. Hadlig Chages Ay chages doe to the storage area ca be tracked by addig a evet listeer ito our code. The evet gets triggered o the widow object wheever the data i the storage area actually chages. The evet is ever triggered i the sessio that iitiated it but gets fired for other tabs or the sessios. if(widow.addevetlisteer){ widow.addevetlisteer("storage",chage_tracked,false); else{ widow.attachevet("ostorage",chage_tracked); fuctio chage_tracked(e) { if(e.key == "empname") { alert('the value for ' + e.key + ' was chaged from' + e.oldvalue + ' to ' + e.ewvalue); The above code adds a evet listeer that calls the chage tracked method asychroously wheever ay chages are doe to the storage area. chage tracked() method keeps the track of the chages doe to the value of the key empname. If ay chages are doe, the it alerts the user with the chages. Use Cases Storig simple data that eeds to remai persistet after the user has browsed away from the applicatio or closed the Web browser Savig game state, avigatio locatio, or storig some specific iformatio that ca be used across the etire Web applicatio Itimatig the user about the chages doe (for example, accout o.) if the same page is opeed i multiple tabs 8
9 HTTP Cookies versus Webstorage HTTP Cookies suffer from limited data storage (e.g. 4KB), whereas the data storage capacity of Webstorage API for most of the browsers is 5MB as per w3c specificatio with a exceptio to IE8 (ad upwards) that supports up to 10MB. Cookies limit the accessibility of data to a certai domai ame or a URL path where as Webstorage ca limit the access to a certai domai ame, or to domai TLD (like.org) or for the give user sessio. It is possible to iterate through all the key/value pairs i HTTP cookies, whereas i Webstorage, it is ot possible to iterate through keys uless the key is kow. Data stored i cookies are passed o by EVERY request to the server, makig it very slow ad ieffective. However, the Webstorage API data is NOT passed o by every server request ad used ONLY whe asked. Webstorage is more public the cookies. This is the reaso why we eed to take special precautios to esure the security. Offlie Web applicatio API To give the user the experiece of the seamless Web browsig, most of the browsers provide the facility of cachig. But cachig suffers from the followig limitatios: Developers do ot have ay cotrol over the pages to be cached. Hece they caot cache all the files of ay specific applicatio. It does ot provide a reliable way for you to access pages while you are i offlie mode (for example, Airplaes). To overcome the above limitatios, HTML5 comes up with the cocept of Offlie Web applicatio API (AppCache) which provides the followig features: The user ca use cloud fuctios o a mobile device, work offlie with a locally deployed applicatio o a local database, ad share data with the rest of the cloud whe goig olie agai. AppCache caches oly the specified pages that are icluded i the maifest file ad hece it is reliable. With a higher degree of certaity, it gives the user the cotrol of the way the Web applicatios should look whe offlie. 9
10 The followig figure shows the major compoets of a offlie Web applicatio. CSS Maifest HTML Server JavaScript DB Architecture of a Offlie Web Applicatio HTML pages Traditioal Web applicatio cosists of HTML pages that cotai the displayed data ad the reder iformatio. Wheever a user iitiates a evet, it causes a request-respose cycle with a page load ad the executio of associated JavaScript fuctios. Offlie Web applicatio cosists of a sigle HTML page without the eed for loadig of further HTML pages through the request-respose cycles. The whole actio is o oe page. JavaScript These files cotai the fuctios that are useful for hadlig the evets iitiated by a user o the HTML page. Cascadig Style Sheet (CSS) It describes the way HTML page should be redered. For mobile devices, there are various JavaScript/CSS libraries ad frameworks to deliver a ear ative user experiece with Web applicatios (for example, iui for the iphoe). Database The HTML5 stadard itroduced local database storage. It is implemeted i curret versios of the Apple Safari browser. The browser provides a embedded database, with SQLite, that ca be accessed from the JavaScript by processig SQL queries. The busiess data of the applicatio model is stored here. Maifest The maifest file is the madatory deploymet descriptor compoet for a offlie Web applicatio. It simply lists all the files that eed to be loaded. 10
11 Steps to Follow for Creatig Offlie Web App Checkig Browser Compatibility Due to the variatio i browser support, first we should check the compatibility of the browser before availig a applicatio offlie. It ca be doe i two ways: Without usig Moderizer Object Usig the Moderizer Object Without usig the Moderizer object, we ca check the compatibility i the followig maer: fuctio chk_offlie_compatibility(){ if(widow.applicatiocache) { alert('this browser supports offlie Web apps' ); else{ alert('sorry your browser does't support offlie Web app' ); The above code checks the global widow object to see if it supports the applicatio Cache object or ot ad iforms the user about the status accordigly. Usig the Moderizer object, oe ca check the compatibility i the followig maer: if (Moderizr.applicatiocache){ alert('this browser supports offlie Web apps' ); else{ alert('sorry your browser does't support offlie Web app' ); Beefit of usig the Moderizer object is that it ca hadle certai tricky margial cases. For example, i private browsig modes, such as Chrome's icogito mode, a call to widowapplicatio Cache will retur true, however the browser will ot actually be able to write files to the cache. 11
12 Creatig a maifest file This file resides o the server ad decides which files should be stored cliet-side i the browser's AppCache, that ca be used whe the user goes offlie.this file cotais a list of URLs to various resources such as Javascript files, HTML CSS, images ad flashfiles. The maifest file has a basic structure that should start with CACHE MANIFEST.Commets ca be made by puttig # at the begiig of a lie. File ames must be listed exactly as they appear o disk as it is case sesitive. There are three amespaces that ca be icluded multiple times i a maifest file ad those are: CACHE NETWORK FALLBACK Cache This sectio lists all the files that the browser eeds to cache for offlie access. The paths provided ca be either relative or absolute. Iclusio of this header is optioal as this is the default header but if we wat to flag files to be cached aywhere else i the file, we eed to place them uder a explicit CACHE: header. Oly oe file ame per lie is allowed. Wildcards ad fragmeted idetifiers are ot allowed uder this header. A sample of the cache sectio that loads html, css js files alog with few images looks like this: CACHE MANIFEST style.css offliescript.js images/image1.pg images/image2.jpg Files listed i this sectio are ever loaded from the server eve whe the user is coected to the iteret. They are always loaded from the AppCache. Network This declaratio is used to specify files that should ot be cached (for example, a logi page). Files listed i this sectio will ot be loaded from the applicatio cache, but will be retrieved from the server if the browser is olie. We ca specify "*" (the default), which sets the olie white list wildcard flag to "ope", so that resources from other origis will ot be blocked. NETWORK: Logi.html dyamic_script.cgi 12
13 Wheever the user tries to access the files listed i this sectio, he or she gets the ackowledgemet with a appropriate offlie message. Fallback Whe the user tries to access a page that was ot cached, or, somethig that was supposed to be cached but was ot saved correctly, the cache maifest API offers a FALLBACK sectio that poits to a page which will be loaded. For example, whe the browser is offlie ad tries to load somethig that is ot i the applicatio cache, such as a page or JavaScript file listed i the NETWORK sectio, the it ca be redirected to a appropriate page listed i this sectio. The fallback cotet is cached ad used i case the mai cotet does ot load. FALLBACK: offlie.html image1.jpg alt_image.jpg /cgi/scripts/ default.html I the above example, alt_image.jpg is cached by AppCache. If image.jpg caot load, the / represets a wildcard fallback that gets triggered wheever there is a fallback while loadig ay of the.cgi ad/or script files. Usig the Applicatio Cache API To use the files from applicatio cache, we ca use the applicatio Cache API. The widow.applicatiocache object provides evets ad properties that ca be used to deal with data retrieval. Curret status of the applicatio cache ca be checked usig widow.applicatiocache.status, which returs a umeric value mapped to the followig states: 0 ucached If the page is ot liked to the applicatio cache; also, the very first time the applicatio cache is beig dowloaded 1 idle Whe the browser has the latest versio of the AppCache, ad there are o updated versios to dowload, the the status is set to Idle 2 checkig The duratio of whe the page is checkig for a updated maifest file, the the status is set to Checkig 3 dowloadig The duratio of whe the page is actually dowloadig a ew cache (if a updated maifest file has bee detected); the status is set to Dowloadig 13
14 4 update ready Oce the browser fiishes dowloadig that ew cache ad is ready to be used (but is ot beig used yet); durig this time, the status is set as Update ready 5 obsolete I case the maifest file caot be foud, the the status is set to obsolete ad the applicatio cache gets deleted. Evets Certai evets also get fired, depedig o what is goig o with the AppCache at the momet. Checkig This gets fired whe browser is attemptig to dowload the maifest for the first time, or is checkig if there is a updated versio of the maifest file. Noupdate If there is o updated versio of the maifest file o the server, the oupdate is fired. Dowloadig If the browser is dowloadig the cache for the first time, or if it is dowloadig a updated cache, the this is fired. Progress This is fired for each ad every file which is dowloaded as part of the AppCache. Cached This is fired whe all the resources have fiished dowloadig, ad applicatio is cached. Updateready Oce resources have fiished re-dowloadig for a updated cached file, the updateready is called. Oce this happes, the we ca use swapcache() to make the browser to use this ewly updated cache. Obsolete This is fired if the maifest file caot be foud (404 error or 410 error). Error This ca be fired for a umber of reasos. If the maifest file caot be foud, the the applicatio cache dowload process has to be aborted, i which case this evet ca be fired. It ca also be fired i case the maifest file is preset, but ay of the files metioed i the maifest file caot be dowloaded properly. It ca eve be fired i case the maifest file chages while the update is beig ru (i which case the browser will wait a while before tryig agai), or i ay other case where there is a fatal error. 14
15 widow.applicatiocache.update(): This will trigger the applicatio cache dowload process, which is early the same as reloadig the page. It simply checks if the maifest has chaged, ad if so dowloads a fresh versio of all the cotet i the cache widow.applicatiocache.swapcache(): This fuctio tells the browser to start usig the ew cache data if it is available Add the maifest file to the local server Oce the.maifest file is created we eed to add that file to the root Web directory of our applicatio (i case of Apache) which is doe as follows: AddType text/cache-maifest.maifest The above code adds a directive i the.htaccess file. This directive makes sure that every maifest file is served as text/cache-maifest. If the file is ot served as required, the whole maifest will have o effect ad the page will ot be available offlie. Likig maifest file to html page The maifest file oce created ca be added to the html pages with the help of maifest attribute of the <html> elemet. <html maifest="offlie.maifest"> Oce we add the maifest file i our html page we ca ru it to check the fuctioality. At this poit of time we eed to remember the fact that we eed to allow the browser to eable the usage of AppCache, if asked. Checkig for updates For checkig the availability of ay updates i the maifest maually, we ca write the followig code : fuctio oupdateready() { alert('foud ew versio!'); widow.applicatiocache.addevetlisteer('updateready', oupdateready); if(widow.applicatiocache.status === widow.applicatiocache.updateready) { oupdateready(); 15
16 We ca also use the update() to do the same job. widow.applicatiocache.update(): This will trigger the applicatio cache dowload process, which is early the same as reloadig the page. It simply checks if the maifest has chaged, ad if so dowloads a fresh versio of all the cotet i the cache widow.applicatiocache.swapcache(): This fuctio tells the browser to start usig the ew cache data if it is available I Chrome we ca clear the offlie cache by selectig "Clear browsig data..." i the prefereces. Safari has a similar "Empty cache" settig i its prefereces but a browser restart may also be required. I Firefox, the offlie cache data is stored separately from the Firefox profile ext to the regular disk cache: Widows Vista/7: C:\Users\<userame>\AppData\Local\Mozilla\Firefox\Profiles\<salt>.<profile ame>\offliecache Mac/Liux: /Users/<userame>/Library/Caches/Firefox/Profiles/<salt>.<profileame>/OfflieCache I Firefox the offlie cache is ot cleared via Tools -> Clear Recet History I case we have chaged ay of the resources i the AppCache or the offlie Web applicatio, the we eed to chage the cache maifest itself. While chagig the cache maifest, it is recommeded to add commets alog with the versio of chage which helps the maifest file i dowloadig the latest versio of the resources. Browser Support Offlie Web Applicatio API is fully supported by most moder browsers ad mobile phoes icludig: Adroid 2.0+ iphoe 2.1+ Blackberry 5.0+ Firefox 3.5+ Chrome 5.0+ Opera Safari 4.0+ Use cases Offlie Web Applicatio ca be used i the followig applicatios: HTML5 offlie Web applicatios ca be used i case of devices (mobile) that losses iteret coectivity i betwee. It ca be used to view ad write message. We ca also edit documets ad presetatios offlie oboard a flight that does ot have Wi-Fi. 16
17 idexeddb API Key-value pairs used by Webstorage API have a limitatio of 5MB of storage space ad it does ot provide efficiet searchig over values. Eve duplicate values ca be stored usig Webstorage API. To overcome the limitatios of the Webstorage API, idexed DB API was beig itroduced that provides a advaced key-value data maagemet. It is a persistet data store i the browser. idexdb uses a Object Store to store the keys ad their correspodig values. It maitais idexes over the records it stores ad developers use the IdexedDB JavaScript API to locate records by key or by a idex. Each database is scoped by origi, that is the domai of the site that creates the database. The Idexed DB specificatio declares two differet API s: A asychroous API, curretly implemeted by the most moder browsers (IE 10, Chrome 11.0, Firefox 4) A sychroous API that is ot implemeted yet. Differece betwee Relatioal Database ad idexeddb idexeddb is a Object Store. It is ot the same as a Relatioal Database. I a traditioal relatioal data store, we would have a table that stores data i the form of rows where as idexeddb creates a Object Store for a type of data that ca store persist Javascript Objects. Each Object Store ca have a collectio of Idexes that make it efficiet to query ad iterate across. Ulike SQL, it is replaced with a query agaist a idex which produces a cursor that you use to iterate across the result set. Developig a Applicatio usig idexdb Gettig Referece to idexdb To work with IdexedDB, we eed to get a referece. As there is o commo specificatio for achievig it, differet browsers support it i their ow ways. I Google Chrome, we eed to access widow.webkitidexeddb, while o Firefox, we eed to use widow.mozidexeddb. if ('webkitidexeddb' i widow) { widow.idexeddb = widow.webkitidexeddb; widow.idbtrasactio = widow.webkitidbtrasactio; else if ('mozidexeddb' i widow) { widow.idexeddb = widow.mozidexeddb; if (!widow.idexeddb ) { alert("sorry your browser does ot support idexdb"); 17
18 Creatig a database Oce you have access to idexeddb referece, we ca create (or ope) the database. Creatig a database is doe by callig the ope() method of the idexeddb object. if (widow.idexeddb) { dbrequest = widow.idexeddb.ope("demoidb", "A object store for demo purpose."); dbrequest.oerror = errorstatus; dbrequest.addevetlisteer('success', fuctio(e) { ddemodb = dbrequest.result e.result; displayrecords(e);, false); I the above code, DemoDB is the ID for the ewly created database while A object store for demo purpose represets the short descriptio of the database. Every commad is executed asychroously ad geerates a request object with the help of which, we ca hadle the evets osuccess or oerror. Creatig a object store Object stores are like tables form relatioal databases. A database ca cotai multiple object stores ad each store is a collectio of records where each record is a simple key/value pair. The records i a object store are automatically sorted i ascedig order by keys. Oce the database is created, we eed to create a object source as follows: fuctio createobjstore() { var request = demodb.setversio('1.0'); request.oerror = errorstatus; request.osuccess = fuctio(e) { if (!demodb.objectstorenames.cotais('demoobjectstore')) { try { var objectstore = demodb.createobjectstore('demoobjectstore', ull); dblog.ierhtml = "<p>object store created.</p>"; catch (err) { dblog.ierhtml = err.tostrig() ; else { dblog.ierhtml = '<p> Object store already exists. </p>'; 18
19 SetVersio is the place where we ca alter the structure of the database. I this place, we ca create ad delete Object Stores ad build ad remove idexes. A call to setversio returs a IDBRequest object where we ca attach our callbacks. Whe successful, we start to create our Object Stores. Object Stores are created with a sigle call to createobjectstore () method. The method takes a ame of the store ( demoobjectstore ) ad a parameter object. Versio umber chages must be performed uder the cotext of a versio chage trasactio. A trasactio represets a atomic ad durable set of data access. All data that are read or writte to the database will happe usig a trasactio. Each trasactio has a mode which declares what type of iteractios is allowed withi the trasactio. This mode is set whe creatig the trasactio ad remais the same for the lifetime of the trasactio. The available modes are: READ_ONLY READ_WRITE VERSION_CHANGE Addig data to object store Oce the data source is created, we ca store data ito it as follows: fuctio addrecord() { var objectstore = demodb.trasactio(["demoobjectstore"], IDBTrasactio.READ_WRITE).objectStore("demoObjectStore"); var request = objectstore.put( documet.getelemetbyid('txtempname').value, documet.getelemetbyid('txtempid').value, documet.getelemetbyid('txtsal').value); request.oerror = errorstatus; request.osuccess = displayrecords; 19
20 Oce we are ready with the Object Store, we ca add data to it usig the put() method. Whe the call to put is successful, the osuccess evet ( displayrecords ) is called which ca display the data. fuctio displayrecords(e) { var html = []; var trasactio = demodb.trasactio(['demoobjectstore'], IDBTrasactio.READ_ONLY); var request = trasactio.objectstore('demoobjectstore').opecursor(); request.osuccess = fuctio(e) { var cursor = request.result e.result; if (!cursor) { dbresultwrapper.ierhtml = '<ul id="idb-results">' + html.joi('') + '</ul>'; retur; html.push('<li><spa class="keyval">', cursor.key, '</spa> ', ' <spa class="keyval" >', cursor.value, '</spa> ', '<a href="javascript:void(0)" oclick="idexeddbdemo.deletekey( \'', cursor.key, '\')">[X]</a></li>'); cursor.cotiue(); request.oerror = errorstatus; I the above code, we have first gaied the access to the object source with READ_ONLY mode. Oce we have access to the object store, we get a referece to the data existig with the help of opecursor() method. With the help of the cursor we ca iterate multiple records i the object store. The cursor also has a positio which idicates the object it is curretly workig with ad the directio where to the cursor is movig. Deletig data from a object store Data stored i a object store ca be deleted as well with the help of the key that uiquely idetifies that record; this ca be doe as follows: fuctio deleterecord(key) { var trasactio = demodb.trasactio(["demoobjectstore"], IDBTrasactio.READ_WRITE); var objectstore = trasactio.objectstore("demoobjectstore"); if (objectstore.delete) { var request = objectstore.delete(key); else { var request = objectstore.remove(key); / request.oerror = errorstatus; request.osuccess = displayrecords; 20
21 Updatig data Data stored i a object store ca be modified with the help of the key as follows: fuctio updaterecordvalue(key, elemet) { var trasactio = demodb.trasactio(["demoobjectstore"], IDBTrasactio.READ_WRITE); var objectstore = trasactio.objectstore("demoobjectstore"); var request = objectstore.put(elemet.textcotet, key); request.oerror = errorstatus; request.osuccess = displayrecords; Removal of object store Existig object sources ca be removed from the database as ad whe eeded. fuctio removeobjstore() { var request = demodb.setversio("the ew versio strig"); request.oerror = errorstatus; request.osuccess = fuctio(e) { if (demodb.objectstorenames.cotais('demoobjectstore')) { try { if (demodb.deleteobjectstore) { demodb.deleteobjectstore('demoobjectstore'); else { demodb.removeobjectstore('demoobjectstore'); catch (err) { dblog.ierhtml = + err.tostrig() ; else { dblog.ierhtml = "<p> Object store does't exist. </p>"; ; Browser Support idexdb API is fully supported by the followig moder browsers : Firefox 4.0+ Chrome
22 Use Cases Offlie Web applicatio ca be used i the followig applicatios: A idle use of idexed API ca be the case where a retailer moves i a area that has o support for iteret coectivity but still he eeds to visit all the stores i that locality. The etire list of iformatio ca be stored offlie usig idexdb which ca help him out. Coclusio At this poit of time, support for the developmet of offlie Web applicatios uder the light of HTMl5 has limited scope ad is ot supported by most of the browsers available i the market. Differet browser providers are followig differet approaches to achieve the same. This approach is also sufferig from the size costrait as per browser implemetatio. However, goig forward, it is expected that these APIs will be supported by almost all the leadig browsers so that there will be a uified approach for the implemetatio ad users ca get the best out of these. Refereces [1] [2] [3] [4] [5] [6] [7] 22
23 Cotact For more iformatio, cotact Subscribe to TCS White Papers TCS.com RSS: Feedburer: About Tata Cosultacy Services Ltd (TCS) Tata Cosultacy Services is a IT services, cosultig ad busiess solutios orgaizatio that delivers real results to global busiess, esurig a level of certaity o other firm ca match. TCS offers a cosultig-led, itegrated portfolio of IT ad IT-eabled ifrastructure, egieerig ad TM assurace services. This is delivered through its uique Global Network Delivery Model, recogized as the bechmark of excellece i software developmet. A part of the Tata Group, Idia s largest idustrial coglomerate, TCS has a global footprit ad is listed o the Natioal Stock Exchage ad Bombay Stock Exchage i Idia. For more iformatio, visit us at IT Services Busiess Solutios Outsourcig All cotet / iformatio preset here is the exclusive property of Tata Cosultacy Services Limited (TCS). The cotet / iformatio cotaied here is correct at the time of publishig. No material from here may be copied, modified, reproduced, republished, uploaded, trasmitted, posted or distributed i ay form without prior writte permissio from TCS. Uauthorized use of the cotet / iformatio appearig here may violate copyright, trademark ad other applicable laws, ad could result i crimial or civil pealties. Copyright 2012 Tata Cosultacy Services Limited TCS Desig Services I M I 02 I 12
