0% found this document useful (0 votes)
7 views36 pages

HTML5 XP - Session 18

Uploaded by

quandhth2304004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views36 pages

HTML5 XP - Session 18

Uploaded by

quandhth2304004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

y

nl
O
se
U
tre
en
Session: 18
C
h
ec

HTML5 Web Storage


pt
rA
Fo
y
 Explain Web storage in HTML5

nl
 Explain session storage

O
 Explain local storage

se
U
 Explain the Indexed DB API

tre
 Describe a native app

en
 Explain the difference between native apps and HTML5 apps
C
 Describe the advantages of native and HTML5 apps
h
 List the steps to convert HTML5 apps to native apps
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage/ Session 18 2


y
nl
Traditionally, over the last few decades, Web applications have been using

O
cookies to store small amounts of information on a user’s computer.

se
A cookie is a file that stores user-related information and may either be
temporary or permanent.

U
A cookie can be created for login details which can be saved for a specified

tre
period on a user’s computer.

en
 C
Drawbacks of cookies are as follows:
h

Cookies slow down the performance of Web application, as they are included
ec

with every HTTP request


pt

 Cookies cannot be considered as safe means for transmission of sensitive


data
rA

 Cookies cannot store large amount of information, as they have a limitation


Fo

of size of 4 KB
 W3C has designed a specification named Web Storage API which offer a solution
to store data on the client-side
© Aptech Ltd. HTML5 Web Storage / Session 18 3
y
nl
O
Is a W3C specification and certain browsers refer to it as ‘DOM Storage’.

se
U
Provides functionality for storage of data on the client-side that is on user’s
machine.

tre
en
Stores data that can cater for both temporary as well as permanent needs.

C
Offers more control than traditional cookies, and is easy to work with.
h
ec

Was originally a part of the HTML5 specification, but now it is present in a


pt

separate specification and stores a maximum of 5 MB of information per domain.


rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 4


y
 Some key differences between cookies and Web storage are as follows:

nl
O
Cookies are meant to be read on the server-side, whereas Web storage is

se
available only on the client-side.

U
Cookies are sent along with each HTTP request to the server, whereas Web

tre
storage data is not carried over to the server.

en
Cookies result in bandwidth overhead and thus lead to high costs, as they are
sent with each HTTP request. The Web storage is stored on the user’s hard
C
drive, so it costs nothing to use.
h
ec

With cookies, the information data that could be stored is 4 KB, whereas with
Web storage, a large amount of data can be stored upto 5 MB.
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 5


y
nl
Web storage is browser-specific and the location where the Web storage data is
stored depends on the browser.

O
Each browser’s storage is separate and independent, even if it is present on the

se
same machine.

U
HTML5 Web storage is implemented natively in most Web browsers, so one can
use it even when third-party browser plug-in is not available.

tre
 Following table lists the support of various browsers for HTML5 Web storage:

en
Browser
C
Version
h
ec

IE 8.0+
pt

Firefox 3.6+
rA

Safari 4.0+
Fo

Chrome 5.0+

Opera 10.5+

© Aptech Ltd. HTML5 Web Storage / Session 18 6


y
nl
O
Two types of HTML5 Web storage are namely, session storage and local
storage.

se
U
Both session and local storage enable to store around 5 MB of data per domain.

tre
To check for browser support of HTML5 Web storage, a property named

en
localStorage or sessionStorage is available as a global variable for the window
object.

C
If there is no support, the localStorage or sessionStorage property will be
h
undefined.
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 7


y
Code Snippet demonstrates the script to check the support for HTML5 Web

nl
storage in the browser.

O
<!DOCTYPE html>

se
<html>
<head>

U
<title>Support for Web Storage</title>
<script>

tre
function checkSupport() {
if ((‘sessionStorage’ in window) && window[‘sessionStorage’]

en
!== null)
{
C
alert(“Your browser supports Web Storage”);
return;
h
ec
}
alert(“Your browser does not support Web Storage”);
pt

}
</script>
rA

</head>
<body onload=”checkSupport();”>
Fo

</body>
</html>

© Aptech Ltd. HTML5 Web Storage / Session 18 8


y
nl
O
Keeps track of data specific to one window or tab and discards it as soon the
user closes the tab (or window) that he/she was working with.

se
Lasts for the entire duration of the session and hence, is not persistent.

U
tre
Makes use of named key/value pairs which are enclosed within double quotes.

en
Stores the data using the named key, whereas the data is retrieved by referring
to that key.
C
h
Key is a string, whereas the value stored in the key can be of any data type such
ec

as string, boolean, integer, or float. Regardless of the type of data that is stored,
it is actually stored internally as a string.
pt
rA

Storing and retrieving data of other types requires the use of functions to convert
them into the appropriate data types.
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 9


y
 Following table lists some examples of named key/value pairs belonging to

nl
various data types.

O
se
Key Value

U
Name Sarah

tre
book C Programming

en
Email [email protected]

car Toyota Innova C


h
ec

age 28
pt

uservalid true
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 10


y
 Several operations that can be performed with the sessionStorage object are as

nl
follows:

O
Storing and retrieving data - setItem() and getItem() methods are used to store

se
and retrieve data from session storage respectively.

U
 Syntax to use setItem() and getItem() methods is as follows:

tre
 To assign data

en
sessionStorage.setItem(key, value);

where, C
h
ec

key: Is the named key to refer to the data.


pt

value: Is the data to be stored.


rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 11


y
nl
 To retrieve data

O
var item = sessionStorage.getItem(key);

se
where,

U
item: Is the variable into which the data will be saved.

tre
en
key: Is the named key to refer to the data.

C
h
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 12


y
Code snippet demonstrates how to set and retrieve a name using

nl
sessionStorage object.

O
<!DOCTYPE html>

se
<html>
<head>

U
<title>Working with Session Storage</title>
<script>

tre
function testStorage() {
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !==

en
null)
{

C
sessionStorage.setItem(‘name’, ‘Sarah’);
alert(‘The name is: ‘ + sessionStorage.getItem(‘name’));
h
}
ec

}
</script>
pt

</head>
rA

<body onload=” testStorage();”>


</body>
</html>
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 13


y
nl
 Removing data

O
sessionStorage.removeItem(key);

se
where,

U
key: Is the named key to refer to the data.

tre
en
 Clearing data

sessionStorage.clear();
C
h
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 14


y
nl
O
Enables to save data for longer periods on the user’s computer, through the
browser.

se
Data is persistent and can be retrieved when a user visits the site again.

U
tre
Is used, if data needs to be stored for more than a single session.

en
Works in a similar fashion as session storage.
C
h
Uses the same functions, such as setItem(), getItem(), removeItem(), and
ec

clear().
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 15


y
Code snippet demonstrates the use of local storage to store the value of

nl
username field and later, retrieve the value in another Web page.

O
<!DOCTYPE html>

se
<html>
<title> Local Storage </title>

U
<script>
function store() {

tre
if ((‘localStorage’ in window) && window[‘localStorage’] !== null) {

en
var username = document.getElementById(‘username’).value;
localStorage.setItem(‘username’, username);
} else {
C
alert (‘your browser does not support storage’);
h
}
ec

}
function cancel_store() {
pt

if ((‘localStorage’ in window) && window[‘localStorage’] !== null) {


rA

localStorage.removeItem(‘username’);
} else {
Fo

alert (‘your browser does not support storage’);


}
}
© Aptech Ltd. HTML5 Web Storage / Session 18 16

y
Code snippet demonstrates the use of local storage to store the value of

nl
username field and later, retrieve the value in another Web page.

O
se
</script>
</head>

U
<body>
<form method=”get” action=”success.html”>

tre
Username: <input type=”text” id=”username” value=”” size=”20”
onblur=”store()”/>

en
<input type=”submit” value=”Submit”/>
<input type=”reset” Value=”Cancel” onclick=”cancel_store()”/>
</body>
</html> C
h
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 17


y
Code snippet shows the success.html page that retrieves value from the local

nl
storage and displays it in the browser.

O
<!DOCTYPE html>
<head>

se
<title> Local Storage </title>

U
<script>
function print() {

tre
var username = localStorage.getItem(‘username’);
document.getElementById(‘lblMsg’).innerHTML = ‘Username: is <b>’+

en
username+’</b>’;
}
</script>
</head> C
h
<body onload=”print()”>
ec

<label id=”lblMsg”></label><br>
pt

</body>
</html>
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 18


y
nl
O
A database is an organized collection of data.

se
Databases, such as relational database stores the data in the form of tables.

U
tre
A table comprises rows and columns that are used to store data.

en
The representation of data from a table is in the form of records.
C
h
HTML5 has introduced a new Web Storage API which can host Web databases
ec

locally within the user browser.


pt

Web databases are not like relational databases in terms of functionality.


rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 19


y
nl
Indexed Database API is a specification also known as IndexedDB.

O
se
It is basically an object store that can be used to store and manipulate data on
the client-side.

U
The object store is the primary storage mechanism that stores the object in the

tre
database managed locally within the browser.

en
It enables to create an object store of a particular type in which objects can be
persisted using JavaScript.
C
IndexedDB enables to create Web applications with rich query abilities and
h
which can work both online and offline.
ec
pt

IndexedDB supports two types of API namely, synchronous and asynchronous.


rA

The synchronous API can be used with WebWorkers, whereas asynchronous API can
Fo

be used for Web applications.

© Aptech Ltd. HTML5 Web Storage / Session 18 20


y
nl
IndexedDB API is implemented using window.indexedDB object.

O
se
Browsers implement the IndexedDB object with their own prefixes. For example,
Chrome browser uses the webkit prefix, whereas Mozilla supports –moz prefix.

U
tre
 Following table lists the browser support for the IndexedDB API.

en
Firefox Chrome Safari Opera iOS Safari
IE

6.0 - - C - - 3.2
h
ec

7.0 8.0moz - - - 4.0-4.1


pt

8.0 9.0moz 16.0webkit 5.0 - 4.2-4.3


rA

9.0 10.0moz 17.0webkit 5.1 11.6 5.0


Fo

10.0 11.0moz 18.0webkit 6.0 12.0 -

- 12.0moz 19.0webkit - - -

© Aptech Ltd. HTML5 Web Storage / Session 18 21


 Some of the basic constructs of IndexedDB API are as follows:

y
nl
Database - The IndexedDB database comprises more than one object store.

O
Each database contains a name that identifies the origin of the database and a
version number which identifies the lifetime of the database.

se
Object Store - Is the main mechanism to store data in a database. They hold

U
the data stored in the database in the form of records.

tre
Keys - Each record stored in the database is identified by a unique key.

en
Values - Are the data stored in the records.
C
h
Key Path - Is a string that defines how the browser should extract key from a
ec

value. The key from a value can be extracted either in the object store or index.
pt

Index - Is used when the data from the object store is retrieved based on some
rA

other values other than a key.


Fo

Transaction - Any addition or retrieval of the data in a database is performed by


using transaction. Each transaction has a mode, scope, and a request list

© Aptech Ltd. HTML5 Web Storage / Session 18 22


y
Some of the other basic constructs of IndexedDB API are as follows:

nl
Requests - Operations, such as reading or writing on the database is performed

O
using a request. Each request contain attributes, such as flag, source object,
result, and error.

se
U
Cursor - Is a mechanism used to retrieve multiple records from a database.

tre
Key Range - Records from the object stores and indexes are retrieved using

en
keys or key ranges. A key range refers to retrieval of data between specified
bounds based on the keys.
C
h
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 23


y
Steps to implement the IndexedDB API in a Web application are as follows:

nl
O
Open a database

se
Create an object store

U
Start a transaction

tre
Perform some database operations, such as add and retrieve

en
Work with the retrieved results
C
h
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 24


y
 Opening a Database

nl
O
 Code snippet shows the code to open a database

se
var indexedDB = window.indexedDB || window.webkitIndexedDB ||

U
window.mozIndexedDB || window.msIndexedDB;
var request = indexedDB.open(“CompanyDB”, 1);

tre
request.onsuccess = function (event) {
. . .

en
};
request.onerror = function (event) {

C
console.log(“IndexedDB error: “ + event.target.errorCode);
};
h
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 25


y
 Updating Version of a Database

nl
O
After the database is opened, it can be structured by providing a version number
which helps to set up the database.

se
U
 Code snippet shows the code that specifies the version number to the database

tre
var setVrequest = db.setVersion(“1.99”);
setVrequest.onsuccess = function(event) {

en
. . .
}
C
h
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 26


y
 Creating the Object Store

nl
O
Structure of IndexedDB database facilitates the storage of multiple object stores.

se
U
Object store is created using createObjectStore() method which accepts two
arguments namely, the store name and a parameter object.

tre
 Code snippet demonstrates the code to create an object store named employee

en
in the CompanyDB database.
var employeeData = [
C
{ name: “John Smith”, email: “[email protected]” },
h
{ name: “Jill Patrick”, email: “[email protected]” },
ec

{ name: “Rock Ethan”, email: “[email protected]” },


{ name: “Daniel Andrew”, email: “[email protected]” }
pt

];
rA

var objectStore = db.createObjectStore(“employee”, {


keyPath: “id”, autoIncrement: true });
for (i in employeeData) {
Fo

objectStore.put(employeeData[i]);
alert(“Record added”);
} HTML5 Web Storage / Session 18 27
© Aptech Ltd.
y
 Creating a Transaction

nl
O
To perform database operation, such as retrieving data from the object store,
IndexedDB provides a IDBTransaction object.

se
U
This object can be created in three mode namely, read-only, read-write, and
snapshot.

tre
 Code snippet demonstrates the code to retrieve data from the employee object

en
store using the get() function of the transaction object.

var trans C= db.transaction([“employee”],


h
IDBTransaction.READ_WRITE).objectStore(“employee”);
ec

var request = trans.get(2);


request.onerror = function(event) {
pt

// Handle errors!
rA

};
request.onsuccess = function(event) {
// Do something with the request.result!
Fo

alert(“Name: “ + request.result.name);
};
© Aptech Ltd. HTML5 Web Storage / Session 18 28
y
 Opening a Cursor

nl
O
Cursor is used to retrieve multiple records from an object store.

se
U
They can be used when the value of key path is not known. They are part of a
transaction and are opened for a particular object store.

tre
 Code snippet demonstrates the code to retrieve multiple records from the

en
employee object store.

C
store = db.transaction(“employee”).objectStore(“employee”);
h
store.openCursor().onsuccess = function(event) {
ec

var cursor = event.target.result;


if (cursor) {
pt

alert(“Name for id “ + cursor.key + “ is “ +


rA

cursor.value.name);
cursor.continue();
}
Fo

};

© Aptech Ltd. HTML5 Web Storage / Session 18 29


y
 Design limitations for IndexedDB API used for client-side storage of data are as

nl
follows:

O
Internationalized sorting deals with sorting of string data. As the database does

se
not follow any international order for storing data, internationalized sorting is not
supported by the API.

U
tre
IndexedDB API does not synchronize client-side database with the server-side
databases.

en
C
IndexedDB API supports querying the client-side database, but does not support
the use of operators, such as LIKE that is used by Structured Query Language
h
(SQL).
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 30


y
nl
O
A native application also known as native app is an application program that is
built for using it on a particular device or platform.

se
U
A native app, when compared with Web app is installed on a device and has a
faster response, because it has a direct user interface.

tre
en
BlackBerry Messenger (BBM) is a native app available on blackberry mobile
devices.
C
h
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 31


y
nl
HTML5 Web apps are accessible and used on any devices through Web
browser similar to the mobile Web site.

O
se
Web apps have the ability of offline access which means that the user need not
have a network connection.

U
 Following table lists differences between the native apps and HTML5 apps.

tre
en
Native Apps HTML5 Apps

C
Native Apps runs on iOS and Android devices that
can be downloaded or purchased from the online
HTML5 Apps runs on a Web server, usually in a
Web browser.
h
app stores.
ec

Native Apps use programming language, such as Web developers use HTML, JavaScript, and CSS.
pt

Java for Android devices and Objective C for iOS They need to acquire the skills of Java and
rA

devices. objective C for writing native applications.


Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 32


y
Main advantage of using HTML5 is to create applications that executes on a wide

nl
range of devices easily. Some of the reasons to develop HTML5 applications are as

O
follows:
Users cannot identify the differences - Cannot identify whether they are

se
working on a hybrid HTML5-native application or a fully native application or an
HTML5 application.

U
Users adjust styles for devices - HTML5 apps can be viewed on any devices

tre
that contains Web browser.

en
Upcoming functionalities - HTML5 does not support all features on a device,
but it is coming up with new functionalities.
C
h
Improving Performance - Many developers learn new methods to improve the
ec

performance of Web.
pt

Independent device - If the developers want that their application to be used by


a large number of users, then they should design and develop applications for
rA

both mobile users as well as desktop users.


Fo

Developers are not locked in app stores - HTML5 developers are not
restricted to an app store. Instead, they can create applications and sell them
like any other Web page.
© Aptech Ltd. HTML5 Web Storage / Session 18 33

y
Major advantage of native apps over HTML5 apps is that they are faster than

nl
HTML5 apps. Native apps provide more benefits over HTML5 apps. These are as

O
follows :

se
Providing access to device hardware - There are no APIs available for
accelerometers, cameras, or any other device hardware for HTML5 apps.

U
Uploading Files - Native apps can access the file system in Android and some

tre
files in iOS. However, the HTML5 file API does not work on Android or iOS.

en
Push Notifications - The push notifications are sent always with an open IP
connection to applications on the iOS device.
C
h
Accessing device files - Native apps communicate with files on devices, such
ec

as contacts and photos. However, these files cannot be seen from HTML5 app.
pt

Superior graphics than HTML5 - HTML5 has a canvas element, but it will not
rA

create a full 3D experience.


Fo

Offline access - HTML5 provides access to offline Web applications. However,


a native app is stored on local machine, so the users does not require access to
the Web to work with the application.
© Aptech Ltd. HTML5 Web Storage / Session 18 34

y
Users have a choice of developing their application in HTML5 and convert them

nl
into a native app

O
 Users can use some tools to convert an HTML5 app to Native app and they are as
follows:

se
U
tre
PhoneGap - Is an HTML5 app that allows the user to create native apps with
Web technologies and is accessible to app stores and APIs.

en
C
Appcelerator - Is a cross-platform mobile application development support and
allows the users to create Android, iOS, and mobile Web apps.
h
ec
pt
rA
Fo

© Aptech Ltd. HTML5 Web Storage / Session 18 35


y
Web Storage is a W3C specification that provides functionality for storing data

nl
on the client-side for both temporary as well as permanent needs.

O
 HTML5 Web applications make use of Web storage to implement client-side

se
persistent storage and they are: session storage and local storage.

U
 Session storage keeps track of data specific to one window or tab.

tre
 The setItem() and getItem() methods are used to store and retrieve the data

en
from session storage.

 C
Local storage enables to save data for longer periods on the user’s computer,
h
through the browser.
ec


pt

IndexedDB API is basically an object store that can be used to store and
manipulate data on the client-side.
rA

 A native application also called as native app is an application program that is


Fo

built for a particular device or platform.

© Aptech Ltd. HTML5 Web Storage / Session 18 36

You might also like